本地缓存使用实践

一、缓存选择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<String, String> 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<String, String> 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<String> 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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值