Spring Cache使用方法与Spring对事务管理的配置相似。SpringCache的核心就是对某个方法进行缓存,其实质就是缓存该方法的返回结果,并把方法参数和结果用键值对的方式存放到缓存中,当再次调用该方法使用相应的参数时,就会直接从缓存里面取出指定的结果进行返回
那么使用 Redistemplate 和 使用注解有什么区别呢?
- 区别就是 Redistemplate 偏向于底层,可以设置缓存时间等其他操作
- 使用注解方式不能设置缓存时间,只是简单地存储和删除缓存操作
- 那么这么做的目的就是因为Springboot更偏向于工具的兼容性
1. 常用注解
@EnableCaching
: 开启缓存支持@Cacheable
: 使用这个注解的方法在执行后会缓存其返回结果(存储数据到缓存)@CacheEvict
: 使用这个注解的方法在其执行前或执行后移除Spring Cache中的某些元素(删除缓存)
2. 环境配置
pom.xml
<!--redis 配置-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
application.yml
server:
port: 9005
spring:
datasource:
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/xxx?useUnicode=true&characterEncoding=utf-8&useSSL=false
username: root
password: root
jpa:
database: MySQL
show-sql: true
redis: # redis配置,如果端口号是6379默认端口,那么只需要写地址就行
host: 123.56.153.90
3. 使用缓存
3.1 Application启动类
添加注解 @EnableCaching
开启缓存支持
package com.tensquare.gathering;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
@SpringBootApplication
@EnableCaching
public class GatheringApplication {
public static void main(String[] args) {
SpringApplication.run(GatheringApplication.class, args);
}
}
3.2 缓存添加
示例 : 在执行按ID查询操作时,添加数据到缓存中
/**
* 根据ID查询实体
* @Cacheable : 把返回结果添加到缓存中
* (value = "gathering",key = "#id")
* value就是键的名称
* key是数据加密的盐
* #id 使用参数中的id作为盐
* 需求: 把findById返回的结果添加到缓存中
*/
@Cacheable(value = "gathering", key = "#id")
public Gathering findById(String id) {
return gatheringDao.findById(id).get();
}
3.3 缓存删除
/**
* @CacheEvict : 调用方法时删除缓存
* (value = "gathering", key = "#gathering.id")
* value就是键的名称
* key是数据加密的盐,
* #gathering.id 使用参数中的id作为盐
* 需求: 执行修改方法时,把 key为 gathering 的缓存删除
*/
@CacheEvict(value = "gathering", key = "#gathering.id")
public void update(Gathering gathering) {
gatheringDao.save(gathering);
}