SringCache
springcache是spring框架开发的一个缓存的框架它支持redis的缓存,接下来我讲解一个如何使用,使用它之前引入spring-boot-starter-data-redis依赖
先让我们看看springcache中常用的注解
- @EnableCaching:开启缓存功能
- @Cacheable:定义缓存,用于触发缓存
- @CachePut:定义更新缓存,触发缓存更新
- @CacheEvict:定义清除缓存,触发缓存清除
- @Caching:组合定义多种缓存功能
- @CacheConfig:定义公共设置,位于class之上
接下来我将注解一个个详细讲解
注意!!!!要导入依赖,启动类要标注@EnableCaching,缓存对象要序列化缺一不可
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
1.@EnableCaching:
你要用springcache的缓存功能就要开启 使用该注解在你的springboot启动类加上该注解就是启动
你的application.ynl配置文件还要有 redis的连接配置
spring:
redis:
database: 0
host: localhost
2.@Cacheable
先一个小demo来打样

此时看看你的redis里的数据
redis存的数据都序列化了 因为SpringCache封装RedisTemplate,而RedisTemplate使用的是JdkSerializationRedisSerializer,如果你想存的数据看的懂我后面有解决方案

可以看到redis数据库的数据是你这个接口返回的对象的序列化,如果你返回的对象没有实现序列化就会报错,存入不了redis中,因为java存取都要经过序列化和反序列化才可以
此时你再访问一下 他就不会进入这个接口的方法内,直接从缓存中拿到对应的key给你返回
运行流程:
@Cacheable方法运行之前,先去查询Cache(缓存组件),按照cacheNames/value指定的名字获取,第一次获取缓存如果没有Cache组件会自动创建。
名称 | 解释 |
---|
value | 缓存的名称,必须指定至少一个 例如: @Cacheable(value=”mycache”) 或者 @Cacheable(value={”cache1”,”cache2”} |
cacheNames | 和value是一样的作用和用法 |
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”) |
sync | 是否使用异步模式,是否启用异步模式 |
keyGenerator | key的生成器;可以自己指定key的生成器的组件id,key/keyGenerator:二选一使用; |
cacheManager | 指定缓存管理器;或者cacheResolver指定获取解析器 作用得到缓存集合 |
cacheResolver | 指定获取解析器,作用得到缓存集合 |
3.@CachePut
@CachePut既调用方法,又更新缓存数据;同步更新缓存。简单来说就是用户修改数据同步更新缓存数据。
老样子先一个demo打样

注意: 该注解的value/cahceNames 和 key 必须与要更新的缓存相同,也就是与@Cacheable 相同。
4.@CacheEvict
还是先打个样

测试结果一访问这个接口在这个接口方法执行完后就会清空指定value的缓存
名称 | 解释 |
---|
… | … |
同上 | 同上 |
allEntries | 指定清除这个缓存中所有的数据,示例:@CachEvict(value=”emp”,allEntries=true) |
beforeInvocation | 示例: @CachEvict(value=”emp”,beforeInvocation=true) 代表清除缓存操作是在方法运行之前执行,无论方法是否出现异常,缓存都清除示例: @CachEvict(value=”emp”,beforeInvocation=false)(默认)缓存的清除是否在方法之前执行 , 默认代表缓存清除操作是在方法执行之后执行;如果出现异常缓存就不会清除 |
5.@Caching
@Caching 用于定义复杂的缓存规则
@Caching(
cacheable = {
@Cacheable(value="emp",key = "#lastName")
},
put = {
@CachePut(value="emp",key = "#result.id"),
@CachePut(value="emp",key = "#result.email")
}
evict = {
@CacheEvict(value="emp",key = "#result.good")
}
)
public Employee getEmpByLastName(String lastName){
return employeeMapper.getEmpByLastName(lastName);
}
名称 | 解释 |
---|
cacheable | 用于指定多个缓存设置操作 |
put | 用于指定多个缓存更新操作 |
evict | 用于指定多个缓存失效操作 |
6.全局配置 @CacheConfig
当我们需要缓存的地方越来越多,可以使用@CacheConfig(cacheNames = {“emp”})注解来统一指定value的值,这时可省略value,如果你在你的方法依旧写上了value,那么依然以方法的value值为准。
例子:
@CacheConfig(cacheNames = {"emp"}, )
public class EmployeeServiceImpl implements EmployeeService {
@Override
@Cacheable( key = "targetClass + methodName +#p0")
public Employee getEmp(Integer id){
Employee emp = employeeMapper.getEmpById(id);
return emp;
}
}
7.主键生成策略 keyGenerator
@Configuration
public class CacheConfig {
@Bean("cacheKeyGenerator")
public KeyGenerator keyGenerator() {
return (target, method, params) -> (method.getName() + " [ " + Arrays.asList(params) + " ]");
}
}
可以在@CacheConfig指定生成策略,也可以在@Cacheable/@CachePut/@CacheEvict指定key生成策略
@CacheConfig(cacheNames = {"emp"}, keyGenerator = "cacheKeyGenerator")
public class EmployeeServiceImpl implements EmployeeService {
@Override
@Cacheable()
public Employee getEmp(Integer id){
Employee emp = employeeMapper.getEmpById(id);
return emp;
}
}
当我们想给这些缓存弄个过期时间又该怎么做
注意: 我这里加了一个redis将java对象以看得懂的形式存入的配置这样我们就可以在redis数据库中看到存的内容是什么了,这里这个对象一定要有无参构造否则会报错

@Configuration
public class CacheConfig {
@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
return new RedisCacheManager(
RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory),
this.getRedisCacheConfigurationWithTtl(600),
this.getRedisCacheConfigurationMap()
);
}
private Map<String, RedisCacheConfiguration> getRedisCacheConfigurationMap() {
Map<String, RedisCacheConfiguration> redisCacheConfigurationMap = new HashMap<>();
redisCacheConfigurationMap.put("Info", this.getRedisCacheConfigurationWithTtl(120));
return redisCacheConfigurationMap;
}
private RedisCacheConfiguration getRedisCacheConfigurationWithTtl(Integer seconds) {
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
redisCacheConfiguration = redisCacheConfiguration.serializeValuesWith(
RedisSerializationContext.SerializationPair.fromSerializer(jsonSerializer())
).entryTtl(Duration.ofSeconds(seconds));
return redisCacheConfiguration;
}
private RedisSerializer jsonSerializer() {
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
return jackson2JsonRedisSerializer;
}
}
在以上的注解的例子的使用看到很多#xxx的东西这是SpEl语法所以我们也要简单熟悉SpEl(Spring Expression Language)
名称 | 位置 | 描述 | 示例 |
---|
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 | 执行上下文 | 当前当前被调用的方法的参数,如findArtisan(String name)可以通过#name获得参数 | #name |
Argument Name | 执行上下文 | 当前被调用的方法的参数,如findArtisan(Artisan artisan),可以通过#artsian.id获得参数 | #artsian.id |
result | 执行上下文 | 方法执行后的返回值(仅当方法执行后的判断有效,如 unless cacheEvict的beforeInvocation=false) | #result |
掌握这些你就可以方便操纵存取redis,但是涉及一些复杂的业务这些功能就不足以满足我们的需求,这时候有jedis以及RedisTemplate和StringRedisTemplate和redisson等API框架等着我们去学习
一键查询淘宝/拼多多内部优惠券,每日大额外卖红包,购物省钱的宝藏工具
