一、实现功能
通过spring的缓存机制,通过spring cache启动spring缓存,以及通过Redis实现缓存。
二、spring cache基本参数
1.@EnableCaching 启用缓存注解,放置位置:注释在启动类或者配置类上
2.@Cacheable 有则用缓存,没有则运行方法
(1)作用:Cacheable表示方法结果可以被缓存,第一次运行方法后,结果即被缓存;以后调用直接返回缓存的结果,不再调用方法体执行。
3.@CacheEvict表示收回缓存:每次调用都会运行,每次运行都会清除缓存
(1)作用:表示收回缓存,一定会执行方法体,每次运行都会清除缓存,收回缓存。
(2)参数allEntries:当allEntries=true则不管key,清除cacheName下所有key的缓存
(3)参数Beforelnvocation:当Beforelnvocation=true,执行方法前清除,默认是执行方法后清除
4.@CachePut
(1)作用:更新缓存,每次都会执行方法,会按照参数中设置的缓存名(cacheNames)和key,将方法的返回值更新缓存
5.@CacheConfig
(1)作用:做统一cacheNames名字配置,写在@Service等类上面,替代cacheNames
6.注意
(1)上文2,3,4注释在@service组件上的公共方法,这些方法需要外部调用。
三、spring cache步骤
1.在启动类注解@EnableCaching开启缓存
@EnableCaching
@EnableScheduling
@EnableAsync
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
2.缓存方法,添加注解@Cacheable、@CacheEvict或者@CachePut
@CacheEvict(cacheNames="counter", key="#id")
@DeleteMapping("/{id}")
public Map<String, Object> deleteOne(@PathVariable int id){
if(log.isTraceEnabled()) {
log.trace("deleteOne " + id);
}
HashMap<String, Object> map = new HashMap<>();
map.put("id", id);
map.put("message", "counter was cleared");
return map;
}
四、使用Redis缓存服务
1.优势:集群,而且可以设置过期时间
2.步骤
(1)pom依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
(2)application.yml配置
spring:
jackson:
date-format: yyyy-MM-dd
time-zone: GMT+8
serialization:
write-dates-as-timestamps: false
# 下面这几行是配置redis作为缓存服务器
cache:
redis:
time-to-live: 600s # 默认是从不过期,可以设置一个过期时间
redis:
host: 192.168.31.3
port: 6379
jedis:
pool:
max-active: 5
max-idle: 10
max-wait: 10000
logging:
file: target/app.log
level:
ROOT: INFO
cn.devmgr: TRACE
(3)使用
@Autowired
private RedisTemplate redisTemplate;//操作key-value都是对象
/**
* Redis五大类型数据
* redisTemplate.opsForValue();[String(字符串)]
* redisTemplate.opsForList();[List(列表)]
* redisTemplate.opsForSet();[Set(集合)]
* redisTemplate.opsForHash();[Hash(散列)]
* redisTemplate.opsForZSet();[ZSet(有序集合)]
*/
public void test() {
redisTemplate.opsForValue().set("string_string","string_string");
redisTemplate.opsForList().rightPush("listright","string_string");
redisTemplate.opsForSet().add("set","set1","set2");
}
(4)具体程序中应用
@Autowired RedisTemplate<?, ?> redisTemplate;
@GetMapping
public Map<String, Object> getAll() {
//下面是在程序中使用redisTemplate的例子,并且设置了这个key一分钟后过期
String key = "CACHE-DATE";
@SuppressWarnings("unchecked")
RedisTemplate<String, Date> rt = (RedisTemplate<String, Date>) redisTemplate;
Date d = rt.opsForValue().get(key);
if( d == null) {
d = new Date();
rt.opsForValue().set(key, d);
Calendar c = Calendar.getInstance();
c.add(Calendar.MINUTE, 1);
rt.expireAt(key, c.getTime()); //设置1分钟后过期
if(log.isTraceEnabled()) {
log.trace("set date " + d + " to cache");
}
}else {
if(log.isTraceEnabled()) {
log.trace("date form cache is " + d);
}
}
Map<String, Object> result = new HashMap<>();
return result;
}
五、参考
1.源码:https://github.com/gexiangdong/tutorial/tree/master/section-08
2.葛香东老师课程
https://study.163.com/course/courseLearn.htm?courseId=1005213034#/learn/video?lessonId=1052750212&courseId=1005213034
3.史上最全的Spring Boot Cache使用与整合
https://www.cnblogs.com/yueshutong/p/9381540.html
4.RedisTemplate用法详解
https://blog.csdn.net/weixin_40461281/article/details/82011670