我是靠谱客的博主 酷酷斑马,这篇文章主要介绍基于Caffeine动态创建本地全局缓存内容总结,现在分享给大家,希望可以做个参考。

文章目录

  • 内容
  • 总结


内容

基于Caffeine写的动态创建本地缓存,总感觉存在问题,希望得到各位大神的指教。

以下是本篇文章正文内容,望多指教

代码如下(示例):

public class Caches {
private Caches() {
}
private static class CacheUtil{
private static final Caches CACHE = new Caches();
private static final Map<String,String> KEY_MAP = new ConcurrentHashMap<>(
);
private static final Map<String,Cache<String, Object>> CACHE_MAP = new ConcurrentHashMap<>(
);
}
public void put(String key,Object val,long duration, TimeUnit unit){
String cacheKey = String.valueOf( unit ).concat( ":" ).concat( String.valueOf( duration ) );
CacheUtil.KEY_MAP.put( key,cacheKey );
CacheUtil.CACHE_MAP.putIfAbsent( cacheKey, Caffeine.newBuilder()
.expireAfterWrite( duration, unit )
.maximumSize(100)
.build());
CacheUtil.CACHE_MAP.get( cacheKey ).put( key,val );
}
//默认1小时
public void put(String key,Object val){
long duration = 1000*60*60;
TimeUnit unit = TimeUnit.MILLISECONDS;
String cacheKey = String.valueOf( unit ).concat( ":" ).concat( String.valueOf( duration ) );
CacheUtil.KEY_MAP.put( key,cacheKey );
CacheUtil.CACHE_MAP.putIfAbsent( cacheKey, Caffeine.newBuilder()
.expireAfterWrite( duration, unit )
.maximumSize(100)
.build());
CacheUtil.CACHE_MAP.get( cacheKey ).put( key,val );
}
public Object get(String key){
if( null == CacheUtil.KEY_MAP.get( key )){
return null;
}
return CacheUtil.CACHE_MAP.get( CacheUtil.KEY_MAP.get( key ) ).getIfPresent( key );
}
public static Caches buildCache(){
return CacheUtil.CACHE;
}
}

总结

总感觉有什么不妥的地方,希望哪位大神能指教下。

最后

以上就是酷酷斑马最近收集整理的关于基于Caffeine动态创建本地全局缓存内容总结的全部内容,更多相关基于Caffeine动态创建本地全局缓存内容总结内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(115)

评论列表共有 0 条评论

立即
投稿
返回
顶部