Spring Boot 整合 Cache
目录
一、Spring缓存抽象
Spring从3.1开始定义了org.springframework.cache.Cache 和 org.springframework.cache.CacheManager接口来统一不同的缓存技术;并支持使用JCache(JSR-107)注解简化我们开发;
-
Cache接口为缓存的组件规范定义,包含缓存的各种操作集合;
-
Cache接口下Spring提供了各种xxxCache的实现;如RedisCache,EhCacheCache ,ConcurrentMapCache等;
-
每次调用需要缓存功能的方法时,Spring会检查检查指定参数的指定的目标方法是否已经被调用过;如果有就直接从缓存中获取方法调用后的结果,如果没有就调用方法并缓存结果后返回给用户。下次调用直接从缓存中获取。
-
使用Spring缓存抽象时我们需要关注以下两点;
1、确定方法需要被缓存以及他们的缓存策略
2、从缓存中读取之前缓存存储的数据
二、几个重要概念&缓存注解
名称 | 解释 |
---|---|
Cache | 缓存接口,定义缓存操作。实现有:RedisCache、EhCacheCache、ConcurrentMapCache等 |
CacheManager | 缓存管理器,管理各种缓存(cache)组件 |
@Cacheable | 主要针对方法配置,能够根据方法的请求参数对其进行缓存 |
@CacheEvict | 清空缓存 |
@CachePut | 保证方法被调用,又希望结果被缓存。 与@Cacheable区别在于是否每次都调用方法,常用于更新 |
@EnableCaching | 开启基于注解的缓存 |
keyGenerator | 缓存数据时key生成策略 |
serialize | 缓存数据时value序列化策略 |
@CacheConfig | 统一配置本类的缓存注解的属性 |
@Cacheable/@CachePut/@CacheEvict 主要的参数
名称 | 解释 |
---|---|
value | 缓存的名称,在 spring 配置文件中定义,必须指定至少一个 例如: @Cacheable(value=”mycache”) 或者 @Cacheable(value={”cache1”,”cache2”} |
key | 缓存的 key,可以为空,如果指定要按照 SpEL 表达式编写, 如果不指定,则缺省按照方法的所有参数进行组合 例如: @Cacheable(value=”testcache”,key=”#id”) |
condition | 缓存的条件,可以为空,使用 SpEL 编写,返回 true 或者 false, 只有为 true 才进行缓存/清除缓存 例如:@Cacheable(value=”testcache”,condition=”#userName.length()>2”) |
unless | 否定缓存。当条件结果为TRUE时,就不会缓存。 @Cacheable(value=”testcache”,unless=”#userName.length()>2”) |
allEntries (@CacheEvict ) | 是否清空所有缓存内容,缺省为 false,如果指定为 true, 则方法调用后将立即清空所有缓存 例如: @CachEvict(value=”testcache”,allEntries=true) |
beforeInvocation (@CacheEvict) | 是否在方法执行前就清空,缺省为 false,如果指定为 true, 则在方法还没有执行的时候就清空缓存,缺省情况下,如果方法 执行抛出异常,则不会清空缓存 例如: @CachEvict(value=”testcache”,beforeInvocation=true) |
三:SpEL上下文数据
Spring Cache提供了一些供我们使用的SpEL上下文数据,下表直接摘自Spring官方文档:
名称 | 位置 | 描述 | 示例 |
---|---|---|---|
methodName | root对象 | 当前被调用的方法名 | #root.methodname |
method | root对象 | 当前被调用的方法 | #root.method.name |
target | root对象 | 当前被调用的目标对象实例 | #root.target |
targetClass | root对象 | 当前被调用的目标对象的类 | #root.targetClass |
args | root对象 | 当前被调用的方法的参数列表 | #root.args[0] |
caches | root对象 | 当前方法调用使用的缓存列表 | #root.caches[0].name |
Argument Name | 执行上下文 | 当前被调用的方法的参数,如findArtisan(Artisan artisan),可以通过#artsian.id获得参数 | #artsian.id |
result | 执行上下文 | 方法执行后的返回值(仅当方法执行后的判断有效,如 unless cacheEvict的beforeInvocation=false) | #result |
注意:
1.当我们要使用root对象的属性作为key时我们也可以将“#root”省略,因为Spring默认使用的就是root对象的属性。 如
@Cacheable(key = "targetClass + methodName +#p0")
2.使用方法参数时我们可以直接使用“#参数名”或者“#p参数index”。 如:
@Cacheable(value="users", key="#id")
@Cacheable(value="users", key="#p0")
以上的知识点适合你遗忘的时候来查阅,下面正式进入学习!
四:开始使用
1. 导入pom 依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
2.然后在启动类注解@EnableCaching开启缓存
@EnableCaching // 开启缓存
@SpringBootApplication
public class CacheApp {
public static void main(String[] args) {
SpringApplication.run(CacheApp.class, args);
}
}
3.缓存@Cacheable 使用
缓存key = user:#userId <br/> 当根据UserId查询User对象为空也会缓存一条空的记录
/**
* 缓存key = user:#userId <br/> 当根据UserId查询User对象为空也会缓存一条空的记录
* @param userId
* @date: 2021/4/15 10:08
* @return: com.zlp.dto.UserResp
*/
@GetMapping("getUserInfo00")
@ApiOperation("获取用户信息-00")
@Cacheable(value = CacheConstants.USER, key = "#userId")
public UserResp getUserInfo00(
@RequestParam(value="userId" ) @ApiParam(name="userId",value="用户ID",required = true) Long userId
){
log.info("getUserInfo.req userId={}", userId);
User user = userService.getById(userId);
return BeanToUtils.doToDto(user, UserResp.class);
}
添加条件判断 condition = "#result != null"
/**
* 缓存key = user:#userId <br/> 当在 @Cacheable 中条添加条件判断属性时(condition = "#result != null")
*
* <p>当根据UserId查询User对象为空 ((condition = "#result != null") == TRUE)不会缓存一条空的记录 </p>
* @param userId
* @date: 2021/4/15 10:08
* @return: com.zlp.dto.UserResp
*/
@GetMapping("getUserInfo01")
@ApiOperation("获取用户信息-01")
@Cacheable(value = CacheConstants.USER, key = "#userId" , condition = "#result != null")
public UserResp getUserInfo01(
@RequestParam(value="userId" ) @ApiParam(name="userId",value="用户ID",required = true) Long userId
){
log.info("getUserInfo.req userId={}", userId);
User user = userService.getById(userId);
return BeanToUtils.doToDto(user, UserResp.class);
}
使用 targetClass + methodName 拼接缓存key
#p0 = param (user)第一个参数(id)
/**
* 缓存key = userResp::class com.zlp.service.impl.UserServiceImplgetUserByUserUser
* (id=1, username=null, password=null, nickname=null, userType=null, status=null, createTime=null, createUser=null, updateTime=null, updateUser=null) <br/>
* 当在 @Cacheable 中条添加条件判断属性时(condition = "#result != null")
*
* <p>当根据UserId查询User对象为空 ((condition = "#result != null") == TRUE)不会缓存一条空的记录 </p>
* @param user
* @date: 2021/4/15 10:08
* @return: com.zlp.dto.UserResp
*/
@GetMapping("getUserByUser")
@ApiOperation("获取用户信息对象")
@Cacheable(value = "userResp" ,key = "targetClass + methodName +#p0")
public UserResp getUserByUser(User user){
Long userId = user.getId();
User users = userService.getById(userId);
return BeanToUtils.doToDto(users, UserResp.class);
}
4.更新@CachePut
@CachePut
注解的作用 主要针对方法配置,能够根据方法的请求参数对其结果进行缓存,和 @Cacheable
不同的是,它每次都会触发真实方法的调用 。简单来说就是用户更新缓存数据。但需要注意的是该注解的value
和 key
必须与要更新的缓存相同,也就是与@Cacheable
相同
/**
* 更新缓存
* @date: 2021/4/15 10:08
* @return: com.zlp.dto.UserResp
*/
@GetMapping("update")
@ApiOperation("修改用户信息")
@CachePut(value = CacheConstants.USER, key = "#userId" , condition = "#result != null" )
public UserResp update(
@RequestParam(value="userId" ) @ApiParam(name="userId",value="用户ID",required = true) Long userId,
@RequestParam(value="nickname" ) @ApiParam(name="nickname",value="昵称",required = true) String nickname
){
log.info("update.req userId={},nickname={}", userId,nickname);
LambdaUpdateWrapper<User> wapper = new LambdaUpdateWrapper<>(new User())
.eq(User::getId,userId)
.set(User::getNickname,nickname);
userService.update(null, wapper);
User user = userService.getById(userId);
return BeanToUtils.doToDto(user, UserResp.class);
}
5. 清除@CacheEvict
@CachEvict
的作用 主要针对方法配置,能够根据一定的条件对缓存进行清空 。
属性 | 解释 | 示例 |
---|---|---|
allEntries | 是否清空所有缓存内容,缺省为 false,如果指定为 true,则方法调用后将立即清空所有缓存 | @CachEvict(value=”testcache”,allEntries=true) |
beforeInvocation | 是否在方法执行前就清空,缺省为 false,如果指定为 true,则在方法还没有执行的时候就清空缓存,缺省情况下,如果方法执行抛出异常,则不会清空缓存 | @CachEvict(value=”testcache”,beforeInvocation=true) |
/**
* 清除一条缓存,key为要清空的数据
* @date: 2021/4/15 9:29
* @return: void
*/
@GetMapping("deleteById")
@ApiOperation("根据用户ID删除")
@CacheEvict(value = CacheConstants.USER, key = "#userId" )
public void deleteById(int userId) {
userService.removeById(userId);
}
/**
* 清空所有user:* 缓存 <br/>
* @date: 2021/4/15 9:29
* @return: void
*/
@GetMapping("deleteAll")
@ApiOperation("删除用户信息")
@CacheEvict(value = CacheConstants.USER,allEntries=true)
public void deleteAll(){
log.info("deleteAll execute ....");
LambdaUpdateWrapper<User> wapper = new LambdaUpdateWrapper<>(new User())
.eq(User::getId,11)
.set(User::getStatus,1);
userService.update(null,wapper);
}
/**
* 方法调用前清空所有缓存user:* 缓存 <br/>
* @date: 2021/4/15 9:29
* @return: void
*/
@GetMapping("deleteAllBeforeInvocation")
@ApiOperation("删除用户信息")
@CacheEvict(value = CacheConstants.USER,beforeInvocation=true)
public void deleteAllBeforeInvocation(){
log.info("deleteAll execute ....");
LambdaUpdateWrapper<User> wapper = new LambdaUpdateWrapper<>(new User())
.eq(User::getId,11)
.set(User::getStatus,1);
userService.update(null,wapper);
}
其他属性
String[] cacheNames() default {}; //与value二选一
String keyGenerator() default ""; //key的生成器。key/keyGenerator二选一使用
String cacheManager() default ""; //指定缓存管理器
String cacheResolver() default ""; //或者指定获取解析器
String condition() default ""; //条件符合则清空
6.组合@Caching
有时候我们可能组合多个Cache注解使用,此时就需要@Caching组合多个注解标签了。
/**
* 更新用户和删除部门信息 缓存
* @date: 2021/4/15 9:29
* @return: void
*/
@Caching(
put = {
@CachePut(value = CacheConstants.USER,key = "#userId"),
},evict = {
@CacheEvict(value = CacheConstants.DEPT,key = "#userId"),
})
@GetMapping("saveMultiCachedUser")
@ApiOperation("保存用户多缓存")
public UserResp saveMultiCachedUser(
@RequestParam(value="userId" ) @ApiParam(name="userId",value="用户ID",required = true) Long userId
){
UserResp userResp = new UserResp();
log.info("deleteAll execute ....");
LambdaUpdateWrapper<User> wapper = new LambdaUpdateWrapper<>(new User())
.eq(User::getId,userId)
.set(User::getStatus,1);
userService.update(null,wapper);
User user = userService.getById(userId);
return BeanToUtils.doToDto(user, UserResp.class);
}
下面讲到的整合第三方缓存组件都是基于上面的已经完成的步骤,所以一个应用要先做好你的缓存逻辑,再来整合其他cache组件。
五:整合EHCACHE
Ehcache是一种广泛使用的开源Java分布式缓存。主要面向通用缓存,Java EE和轻量级容器。它具有内存和磁盘存储,缓存加载器,缓存扩展,缓存异常处理程序,一个gzip缓存servlet过滤器,支持REST和SOAP api等特点。
1.导入依赖
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
2.yml配置
spring:
cache:
type: ehcache
ehcache:
config: classpath:/ehcache.xml
3.ehcache.xml
在resources目录下新建ehcache.xml,注释啥的应该可以说相当详细了
<ehcache>
<!--
磁盘存储:将缓存中暂时不使用的对象,转移到硬盘,类似于Windows系统的虚拟内存
path:指定在硬盘上存储对象的路径
path可以配置的目录有:
user.home(用户的家目录)
user.dir(用户当前的工作目录)
java.io.tmpdir(默认的临时目录)
ehcache.disk.store.dir(ehcache的配置目录)
绝对路径(如:d:\\ehcache)
查看路径方法:String tmpDir = System.getProperty("java.io.tmpdir");
-->
<diskStore path="java.io.tmpdir" />
<!--
defaultCache:默认的缓存配置信息,如果不加特殊说明,则所有对象按照此配置项处理
maxElementsInMemory:设置了缓存的上限,最多存储多少个记录对象
eternal:代表对象是否永不过期 (指定true则下面两项配置需为0无限期)
timeToIdleSeconds:最大的发呆时间 /秒
timeToLiveSeconds:最大的存活时间 /秒
overflowToDisk:是否允许对象被写入到磁盘
说明:下列配置自缓存建立起600秒(10分钟)有效 。
在有效的600秒(10分钟)内,如果连续120秒(2分钟)未访问缓存,则缓存失效。
就算有访问,也只会存活600秒。
-->
<defaultCache maxElementsInMemory="10000" eternal="false"
timeToIdleSeconds="600" timeToLiveSeconds="600" overflowToDisk="true" />
<cache name="myCache" maxElementsInMemory="10000" eternal="false"
timeToIdleSeconds="120" timeToLiveSeconds="600" overflowToDisk="true" />
</ehcache>
整合完毕!
别忘了在启动类开启缓存!
六:整合Redis
Redis 优势
- 性能极高 – Redis能读的速度是110000次/s,写的速度是81000次/s 。
- 丰富的数据类型 – Redis支持二进制案例的 Strings, Lists, Hashes, Sets 及 Ordered Sets 数据类型操作。
- 原子 – Redis的所有操作都是原子性的,意思就是要么成功执行要么失败完全不执行。单个操作是原子性的。多个操作也支持事务,即原子性,通过MULTI和EXEC指令包起来。
- 丰富的特性 – Redis还支持 publish/subscribe, 通知, key 过期等等特性
1.启动Redis
下载地址:https://github.com/MicrosoftArchive/redis/releases
2.导入依赖
就只需要这一个依赖!不需要spring-boot-starter-cache
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
当你导入这一个依赖时,SpringBoot的CacheManager就会使用RedisCache。
如果你的Redis使用默认配置,这时候已经可以启动程序了。
3.配置Redis
spirng
## redis配置
redis:
database: 0
host: 127.0.0.1
password: zlp123456
port: 6379
timeout: 5000
相关文章
- Spring Boot 从1.0 升级到 2.0 所踩的坑
- 基于Spring Boot 2.0的IoT应用集成和使用CSE实践
- 【Spring Boot】Spring Boot之两种引入spring boot maven依赖的方式
- 【Spring Boot】Spring Boot之使用 Java High Level REST Client 整合elasticsearch
- spring boot与jdbcTemplate的整合案例2
- Spring Boot 开发集成 WebSocket,实现私有即时通信系统
- Spring Boot 整合 Log4j2 日志并压测性能
- spring boot properties 编码问题[四]
- spring boot单元测试之十六:junit5:用@Timeout注解判断测试运行是否超时(spring boot 2.4.4)
- spring boot:shardingsphere+druid多数据源整合seata分布式事务(spring boot 2.3.3)
- spring boot:使用多个redis数据源(spring boot 2.3.1)
- spring boot:用cookie保存i18n信息避免每次请求时传递参数(spring boot 2.3.3)
- spring boot: 设计接口站api的版本号,支持次版本号(spring boot 2.3.2)
- spring boot整合freemarker及freemarker基础语法超详细讲解
- spring boot新建非web项目(无需依赖)
- 【面试】Spring Boot读取Yml配置文件的3种方法
- 学习Spring Boot:(十四)spring-shiro的密码加密
- spring boot --- 注解 @Bean 和@Component
- 毕业设计 Spring Boot的校园疫情师生防疫登记备案系统(含源码+论文)
- 全网最完美地解决使用spring boot的@Value(“${xxx}“)注解时报出的错误:Could not resolve placeholder ‘xxx‘ in value “${xxx}“
- Spring Boot整合Spring Data JPA
- 什么是Spring Boot
- 如何选择Spring cloud和 Spring Boot对应的版本
- 【工作流Activiti7】2、Activiti7 与 Spring Boot 及 Spring Security 整合
- 【springboot异步处理】Spring Boot + @Async