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();
}
}
MapDB实现本地缓存
最新推荐文章于 2025-02-25 19:19:52 发布