目录
1 导依赖
<dependency>
<groupId>com.alicp.jetcache</groupId>
<artifactId>jetcache-starter-redis</artifactId>
<version>2.6.2</version>
</dependency>
2 配置文件
spring:
# 解决jetcache循环依赖问题
main:
allow-circular-references: true
jetcache:
# 查看缓存报告:1min后
statIntervalMinutes: 1
# 使用本地缓存
local:
default:
type: linkedhashmap
# 把对象的key转成json字符串
keyConvertor: fastjson
# 使用远程缓存
remote:
default:
type: redis
host: localhost
port: 6379
keyConvertor: fastjson
valueEncoder: java
valueDecoder: java
# 该属性必须要有
poolConfig:
# 最大连接数
maxTotal: 50
# 第2组配置
sms:
type: redis
host: localhost
port: 6379
# 该属性必须要有
poolConfig:
# 最大连接数
maxTotal: 50
3 引导类加注解
@EnableCreateCacheAnnotation和@EnableMethodCache
package com.qing;
import com.alicp.jetcache.anno.config.EnableCreateCacheAnnotation;
import com.alicp.jetcache.anno.config.EnableMethodCache;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
//jetcahce启用缓存的主开关
@EnableCreateCacheAnnotation
//开启方法注解缓存,该注解和@EnableCreateCacheAnnotation一起使用,后面是方法的包
@EnableMethodCache(basePackages = "com.qing")
public class JetCacheApplication {
public static void main(String[] args) {
SpringApplication.run(JetCacheApplication.class, args);
}
}
4 实体类实现序列化
5 在方法上加注解
@Override
//默认过期时间是s
@Cached(name = "book",expire = 60,key = "#id")
public Book getById(Integer id) {
return bookDao.selectById(id);
}
备注:默认使用配置文件里远程default那一套配置
测试
查询第2遍时候不走数据库,走缓存
redis里的数据
yaml配置的查看缓存报告statIntervalMinutes如下
备注
@CacheRefresh 设置在查询上,表示10s刷新进行查询