基于 Redis + Caffeine 做多级缓存
- 背景:在我们的项目中,经常需要查询一些数据,而大部分数据都是不经常改变的,所以我们可以存在缓存中,这里我们使用Caffeine作为本地缓存库,redis分布式缓存来实现
JetCache 是一个 Java 缓存库,旨在提供简洁、高性能且通用的缓存解决方案。它支持多种缓存策略和缓存存储类型,包括本地缓存(如Caffeine、Guava 等)和分布式缓存( Redis、Memcached 等)
Caffeine 是一个高性能的 Java 缓存库,受到了 Google Guava 缓存库的启发。它主要用于实现本地缓存,具有高效的缓存命中率和低延迟的特点。Caffeine 提供了灵活的缓存策略和强大的功能,使其成为许多 Java 应用程序的首选缓存解决方案。
- maven依赖导入
<!-- Caffeine -->
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
<version>3.1.8</version>
</dependency>
<!-- JetCache -->
<dependency>
<groupId>com.alicp.jetcache</groupId>
<artifactId>jetcache-starter-redisson</artifactId>
<version>2.7.5</version>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- Redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
- 配置文件
jetcache:
statIntervalMinutes: 1 # 设置统计信息收集的时间间隔为1分钟
areaInCacheName: false # 禁用在缓存名称中包含区域名称
local:
default:
type: caffeine # 使用Caffeine作为本地缓存实现
keyConvertor: fastjson2 # 使用Fastjson2进行键转换
remote:
default:
type: redisson # 使用Redisson作为远程缓存实现
keyConvertor: fastjson2 # 使用Fastjson2进行键转换
broadcastChannel: ${spring.application.name} # 广播频道名称设置为Spring应用程序名称
keyPrefix: ${spring.application.name} # 键前缀设置为Spring应用程序名称
valueEncoder: java # 使用Java进行值编码
valueDecoder: java # 使用Java进行值解码
defaultExpireInMillis: 5000 # 设置默认过期时间为5000毫秒(5秒)
- 开启注解
在启动类上开启注解@EnableMethodCache
@EnableMethodCache(basePackages = "xx.xx.xx")
public class Application {
}
- 常用注解
@Cached(name = ":user:cache:id:", expire = 3000, cacheType = CacheType.BOTH, key = "#userId", cacheNullValue = true)
@CacheRefresh(refresh = 60, timeUnit = TimeUnit.MINUTES)
@CacheInvalidate(name = ":user:cache:id:", key = "#request.userId")
-
@Cached:为一个方法添加缓存,创建对应的缓存实例,注解可以添加在接口或者类的方法上面,该类必须是spring bean
name:指定缓存实例名称,如果没有指定,会根据类名+方法名自动生成。
expire:超时时间。如果注解上没有定义,会使用全局配置,如果此时全局配置也没有定义,则为无穷大。
cacheType:缓存的类型,支持:REMOTE、LOCAL、BOTH,如果定义为BOTH,会使用LOCAL和 REMOTE组合成两级缓存。
key:使用SpEL指定缓存key,如果没有指定会根据入参自动生成。
cacheNullValue:当方法返回值为null的时候是否要缓存。 -
@CacheRefresh:用于标识这个缓存需要自动刷新
refresh:刷新的时间间隔 timeUnit:时间单位 -
@CacheInvalidate:用于标识这个方法被调用时需要移除缓存
name:指定缓存的唯一名称,一般指向对应的@Cached定义的name。
key:使用SpEL指定key,如果没有指定会根据入参自动生成。