【Caffeine入门】浅谈缓存框架Caffeine

Caffeine是一个基于Java8的高性能缓存框架,号称趋于完美。Caffeine受启发于Guava Cache的API,使用API和Guava是一致的。它借鉴了Guava Cache和ConcurrentLinkedHashMap的设计经验。

在Springboot中使用Caffeine

在工程的pom文件引入caffeine的依赖,如下:

<dependency>
            <groupId>com.github.ben-manes.caffeine</groupId>
            <artifactId>caffeine</artifactId>
            <version>2.6.2</version>
        </dependency>

创建一个抽象类AbstractCaffineCache,该类使用范型来约束缓存的数据类型,并实现了三个方法,put、get、clear。

/**
 * @Author ZhuZiKai
 * @Description
 * @date 2022/3/7 10:44
 */
public abstract class AbstractCaffeineCache<T> {

    protected LoadingCache<String, T> loadingCache;

    abstract LoadingCache<String, T> createLoadingCache();

    public boolean put(String key, T value) {
        if (loadingCache == null) {
            loadingCache = createLoadingCache();
        }
        loadingCache.put(key, value);

        return Boolean.TRUE;
    }

    public T get(String key) {
        if (loadingCache == null) {
            loadingCache = createLoadingCache();
        }
        try {

            return loadingCache.get(key);
        } catch (Exception e) {
            return null;
        }
    }

    public boolean clear(String key) {
        if (loadingCache == null) {
            loadingCache = createLoadingCache();
        }
        loadingCache.invalidate(key);
        return Boolean.TRUE;
    }

}

创建MyCaffeineCache的缓存类,该类缓存类。创建LoadingCache类,该类设置了缓存过期的时间,最大的缓存个数。

/**
 * @Author ZhuZiKai
 * @Description
 * @date 2022/3/7 10:44
 */

public class MyCaffeineCache extends AbstractCaffeineCache {

    /**
     * Caffeine配置说明:
     * initialCapacity=[integer]: 初始的缓存空间大小
     * maximumSize=[long]: 缓存的最大条数
     * maximumWeight=[long]: 缓存的最大权重
     * expireAfterAccess=[duration]: 最后一次写入或访问后经过固定时间过期
     * expireAfterWrite=[duration]: 最后一次写入后经过固定时间过期
     * refreshAfterWrite=[duration]: 创建缓存或者最近一次更新缓存后经过固定的时间间隔,刷新缓存
     * recordStats:开发统计功能
     *
     * @return
     */
    @Override
    LoadingCache createLoadingCache() {
        loadingCache = Caffeine.newBuilder()
                .expireAfterWrite(1000L, TimeUnit.MILLISECONDS)
                .initialCapacity(10)
                .maximumSize(100)
                .recordStats()
                .build((CacheLoader<String, String>) key -> null);
        return loadingCache;
    }
}

将MyCaffeineCache注入到spring ioc中,代码如下:

/**
 * @Author ZhuZiKai
 * @Description
 * @date 2022/3/7 10:45
 */
@Configuration
public class CaffeineCacheConfig {
    @Bean
    public MyCaffeineCache MyCaffeineCache(){
        return new MyCaffeineCache();
    }
}

如何使用。

/**
 * @Author ZhuZiKai
 * @Description
 * @date 2022/1/6 9:45
 */
@Aspect
@Component
@Slf4j
public class IdempotentAspect extends BaseController {

    @Resource
    private MyCaffeineCache cache;

    private static final ThreadLocalUtil threadLocalUtil = new ThreadLocalUtil();

    @Around(value = "@annotation(idempotent)")
    public Object around(ProceedingJoinPoint joinPoint, Idempotent idempotent) throws Throwable {

        UserBO user = getUserBO(request);
        Integer userId = user.getUserId();

        String userRequest = userId + request.getRequestURI();

        threadLocalUtil.setLocalUserRequest(userRequest);

        Object uuid = cache.get(userRequest);
        VerifyUtils.throwWhen(uuid != null, idempotent.value());

        return joinPoint.proceed();

    }

    @AfterReturning(value = "@annotation(idempotent)")
    public void afterReturning(JoinPoint point, Idempotent idempotent) {
        try {
            cache.put(threadLocalUtil.getLocalUserRequest(), UUIDUtil.simpleUUID());
        } finally {
            threadLocalUtil.clearLocalUserRequest();
        }
    }
}

使用本地缓存可以加快页面响应速度,缓存分布式缓存读压力,大量、高并发请求的网站比较适用

Caffeine配置说明:

  • initialCapacity=[integer]: 初始的缓存空间大小
  • maximumSize=[long]: 缓存的最大条数
  • maximumWeight=[long]: 缓存的最大权重
  • expireAfterAccess=[duration]: 最后一次写入或访问后经过固定时间过期
  • expireAfterWrite=[duration]: 最后一次写入后经过固定时间过期
  • refreshAfterWrite=[duration]: 创建缓存或者最近一次更新缓存后经过固定的时间间隔,刷新缓存
  • recordStats:开发统计功能

注意:
expireAfterWrite和expireAfterAccess同时存在时,以expireAfterWrite为准。

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_Romeo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值