栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

本地缓存使用实践

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

本地缓存使用实践

一、缓存选择Guava和Caffeine

Caffeine是一个高性能的Java缓存,有了它完全可以代替Guava Cache,来实现更加高效的缓存;Caffeine采用了W-TinyLFU回收策略,集合了LRU和LFU的优点,提供了一个最佳的命中率,在效率上可以秒杀Guava Cache。

官方性能测试结果:

二、Caffeine使用姿势 1、同步加载
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
 
 
private LoadingCache cache = Caffeine.newBuilder()
    .maximumSize(100L)
    .refreshAfterWrite(30, TimeUnit.SECONDS)
    .expireAfterWrite(60, TimeUnit.SECONDS)
    .build(key -> {
        log.info("LoadingCache.load begin");
        Thread.sleep(2000L);
        log.info("LoadingCache.load end");
        return String.valueOf(number);
    });
 
public String getCache(String key) {
    try {
        number++;
        return cache.get(key);
    } catch (Exception ex) {
        log.error("TestCache.getCache exception", ex);
        return null;
    }
}
3、异步加载
private AsyncLoadingCache asyncCacheLoader = Caffeine.newBuilder()
    .maximumSize(100L)
    .refreshAfterWrite(30, TimeUnit.SECONDS)
    .expireAfterWrite(60, TimeUnit.SECONDS)
    .buildAsync(key -> {
        log.info("AsyncLoadingCache.load begin");
        Thread.sleep(2000L);
        log.info("AsyncLoadingCache.load begin");
        return String.valueOf(number);
    });
 
 
public String getAsyncCache(String key) {
    CompletableFuture future = asyncCacheLoader.get(key);
    try {
        return future.get();
    } catch (Exception ex) {
        log.error("TestCache.getAsyncCache exception", ex);
        return null;
    }
}
4、使用注解 @Cacheable a、配置caffeine
spring:
  cache:
    type: caffeine
    caffeine:
      spec: initialCapacity=10,maximumSize=200,expireAfterWrite=30s
b、开启spring cache

启动类添加@EnableCaching

c、代码示例
@Cacheable("addCache")
public int add(int one, int second) {
    try {
        Thread.sleep(2000);
    } catch (Exception e) {
        log.error("Calculation.add Exception", e);
    }
    return one + second;
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/705111.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号