Ehcache 3.8 简单持久化

Wu Jun 2020-04-15 19:44:06
Categories: > Tags:

1 引入依赖

<dependency>
    <groupId>org.ehcache</groupId>
    <artifactId>ehcache</artifactId>
    <version>3.8.1</version>
</dependency>

2 持久化配置

public class EhcacheHelper {

    private static CacheManager cacheManager;

    public static CacheManager getCacheManager() {
        if(!isAvailable()){
            cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
                    .with(CacheManagerBuilder.persistence(new File("java.io.tmpdir", "EhcacheData")))
                    .withCache("xxxCache",
                            CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
                                    ResourcePoolsBuilder.newResourcePoolsBuilder()
                                            .heap(2000, EntryUnit.ENTRIES)
                                            .offheap(1, MemoryUnit.MB)
                                            .disk(20, MemoryUnit.MB, true)
                            )
                    ).build(true);
        }
        return cacheManager;
    }

    public static void close() {
        if(isAvailable()){
            cacheManager.close();
        }
    }

    public static Boolean isAvailable() {
        return null != cacheManager && cacheManager.getStatus().equals(Status.AVAILABLE);
    }
}

3 使用示例

存放

public void setCache() {
    CacheManager persistentCacheManager = EhcacheHelper.getCacheManager();
    Cache<Long, String> persistentCache = persistentCacheManager.getCache("threeTieredCache", Long.class, String.class);
    for (long i = 0;i < 100;i ++){
        persistentCache.put(i, "这是第:-" + i + "-条信息");
    }

    persistentCache.forEach( cc -> {
        log.info("persistentCache,主键:{},值:{}",cc.getKey(),cc.getValue());
    });

    persistentCacheManager.close();
}

取用

public void getCache() {
    CacheManager persistentCacheManager = EhcacheHelper.getCacheManager();
    Cache<Long, String> persistentCache = persistentCacheManager.getCache("threeTieredCache", Long.class, String.class);

    int count = 0;
    Iterator<Cache.Entry<Long,String>> iterator = persistentCache.iterator();
    while(iterator.hasNext()){
        ++ count;
        Cache.Entry<Long,String> entry = iterator.next();
        log.info("threeTieredCache,主键:{},值:{}",entry.getKey(),entry.getValue());
    }
    log.info("信息的总条数为:{}",count);
    persistentCacheManager.close();
}

4 关闭钩子

public class Application {

    public static void main(String[] args) {
        SpringApplication.run(SkuSyncApplication.class, args);

        //将 hook 线程添加到运行时环境中去
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                EhcacheHelper.close();
                System.out.println("ShutdownHook ==> Ehcache closed");
            }
        });
    }

}