MapDB实现本地缓存

public class Caches {
//MapDB数据库对象
    private DB db;

    //私有的本类的静态变量
    private static Caches cache = null;
    
    private static Map map;

    //初始化本地缓存
    private Caches() {
        boolean flag=init();
        if(flag){
            TimedTask.updateNeNames();
        }

    }

    public Boolean init() {
        //创建数据库数据存储本地文件
        File cacheFile = new File("E:/leo/mapdb/test.db");
        //创建文件夹目录
        cacheFile.getAbsoluteFile().getParentFile().mkdirs();
        //创建MapDB数据库对象
        db = DBMaker.fileDB(cacheFile)
                .fileMmapEnable()
                .checksumHeaderBypass()
                .make();
        //创建Map集合对象,用来存数据
        map = db.treeMap("map").keySerializer(Serializer.STRING)
                .valueSerializer(Serializer.STRING).createOrOpen();
        
        if(!map.isEmpty()){
            return true
        }
    }

    public void load() {
        //业务操作
    }

    //加载数据库的网元,可以定时调用该方法,刷新本地缓存
    public void Update() {
        //将数据库查询的数据写入本地缓存对象
        loadNeNames();
    }

    //提供给外部调用的入口
    public static Caches getInstance() {
        //单例模式
        if (cache == null) {
            synchronized (Caches.class) {
                if (cache == null) {
                    cache = new Caches();
                }
            }
        }
        return cache;
    }
}


package org.pt.pi.mapdb
public class TimedTask {
    public static void update() {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        calendar.set(year, month, day, 00, 00, 00);
        Date defaultdate = calendar.getTime();
        //System.out.println(defaultdate);
        if (defaultdate.before(new Date())) {
            calendar.add(Calendar.DATE, 1);
            defaultdate = calendar.getTime();
        }

        Timer dTimer = new Timer();
        dTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                //System.out.println("当前执行时间");
                Caches.getInstance().Update();
               
            }
        }, defaultdate, 24 * 60 * 60 * 1000);

    }

    public static void main(String[] args) {
        update();

    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

跳舞 D 猴子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值