正文
1、引入依赖,这里我们使用sringboot项目框架,同时使用redis作为远程缓存。于是我们引入
jetcache-starter-redis
依赖,这里我的springboot版本为
2.6.13
如果是非springboot项目可以参考官网说明配置
<dependency>
<groupId>com.alicp.jetcachegroupId>
<artifactId>jetcache-starter-redisartifactId>
<version>2.7.0version>
dependency>
<dependency>
<groupId>redis.clientsgroupId>
<artifactId>jedisartifactId>
<version>4.3.1version>
dependency>
对应的版本说明如下:https://github.com/alibaba/jetcache/blob/master/docs/CN/Compatibility.md
2、修改配置文件,配置redis地址和线程数
jetcache:
# 统计间隔,0表示不统计,开启后定期在控制台输出缓存信息
statIntervalMinutes:15
# 是否把cacheName作为远程缓存key前缀
areaInCacheName:false
# 本地缓存配置
local:
default:# default表示全部生效,也可以指定某个cacheName
# 本地缓存类型,其他可选:caffeine/linkedhashmap
type:linkedhashmap
keyConvertor:fastjson
# 远程缓存配置
remote:
default:# default表示全部生效,也可以指定某个cacheName
type:redis
# key转换器方式n
keyConvertor:fastjson
broadcastChannel:projectA
# redis序列化方式
valueEncoder:java
valueDecoder:java
# redis线程池
poolConfig:
minIdle:5
maxIdle:20
maxTotal:50
# redis地址与端口
host:127.0.0.1
port:6379
更详细的参数配置可参考官网说明:
3、启动类添加注解
@EnableCreateCacheAnnotation
,开启缓存,添加
@EnableMethodCache(basePackages = "com.example.jetcachedemo")
注解,配置缓存方法扫描路径
4、使用缓存可以通过三种方式:
-
方式一(推荐)AOP模式:通过
@Cached
,
@CacheUpdate
,
@CacheInvalidate
注解
@RestController
@RequestMapping("user")
publicclass UserController {
@GetMapping("getRemote")
@Cached(name="userCache:", key = "#id", expire = 3600, timeUnit = TimeUnit.SECONDS, cacheType = CacheType.REMOTE)
public User getRemote(Long id){
// 直接新建用户,模拟从数据库获取数据
User user = new User();
user.setId(id);
user.setName("用户remote"+id);
user.setAge(23);
user.setSex(1);
System.out.println("第一次获取数据,未走缓存:"+id);
return user;
}
@GetMapping("getLocal")
@Cached(name="userCache:", key = "#id", expire = 3600