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

本文介绍了如何在Spring Boot中集成Caffeine作为高性能缓存框架。首先,通过在pom.xml中添加依赖来引入Caffeine。然后,定义了一个抽象类AbstractCaffeineCache,包含put、get和clear方法,并创建了具体的缓存类MyCaffeineCache,设置缓存过期时间和最大容量。接着,将MyCaffeineCache注入到Spring IoC容器中。在实际使用中,通过AOP实现幂等性检查,利用Caffeine缓存减轻数据库压力。Caffeine提供了丰富的配置选项,如初始化容量、最大大小、过期时间和统计功能等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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为准。

Caffeine是一个基于Java 8的高性能缓存库,它提供了多种缓存策略,包括基于时间、大小、权重、最近使用次数等。使用Caffeine缓存,我们可以通过以下步骤来实现: 1. 导入Caffeine库 要使用Caffeine缓存,我们需要在项目中导入Caffeine库。可以使用Maven或Gradle将Caffeine库添加到项目中。 2. 创建缓存对象 在使用Caffeine缓存之前,我们需要创建一个缓存对象。可以使用Caffeine类的静态方法来创建缓存对象,例如: Cache<String, String> cache = Caffeine.newBuilder() .maximumSize(100) .expireAfterAccess(1, TimeUnit.MINUTES) .build(); 这将创建一个最大容量为100,过期时间为1分钟的缓存对象。 3. 向缓存中添加数据 我们可以使用put()方法向缓存中添加数据,例如: cache.put("key1", "value1"); cache.put("key2", "value2"); 4. 从缓存中获取数据 我们可以使用get()方法从缓存中获取数据,例如: String value1 = cache.get("key1", k -> "default"); 这将返回“key1”对应的值“value1”,如果缓存中没有“key1”对应的值,则返回默认值“default”。 5. 删除缓存数据 我们可以使用invalidate()方法删除缓存中的数据,例如: cache.invalidate("key1"); 这将删除缓存中“key1”对应的数据。 6. 清空缓存 我们可以使用invalidateAll()方法清空缓存,例如: cache.invalidateAll(); 这将删除缓存中的所有数据。 这些是使用Caffeine缓存的基本步骤,可以根据具体需求来选择缓存策略和配置参数。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

_Romeo

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

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

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

打赏作者

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

抵扣说明:

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

余额充值