SpringCache快速使用

官方文档

  • 引入依赖
<!--        前提是有redis的依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
  • 已经自动配置的
    CacheAutoConfiguration会导入RedisCacheConfiguration,自动配好了RedisCacheManager这个缓存管理器。
  • 需要配置的
    application.properties
#配置使用redis作为缓存
spring.cache.type=redis
开启缓存,在启动类上添加
@EnableCaching
测试缓存
@Cacheable: Triggers cache population.触发将数据保存到缓存中

@CacheEvict: Triggers cache eviction.触发将数据删除from缓存

@CachePut: Updates the cache without interfering with the method execution.不影响方法执行,更新缓存

@Caching: Regroups multiple cache operations to be applied on a method.组合以上多个操作

@CacheConfig: Shares some common cache-related settings at class-level.在类级别共享缓存的相同配置
  • 简单使用
/**
* //代表当前方法返回结果需要缓存,若缓存中有,不调用方法,如果没有,调用方法最后将方法的结果放入缓存
* 放入category缓存分区中
*/
@Cacheable({"category"})
@Override
public List<CategoryEntity> getFirstLevelCategorys() {
log.info("getFirstLevelCategorys方法调用");
LambdaQueryWrapper<CategoryEntity> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(CategoryEntity::getParentCid, 0);
return baseMapper.selectList(wrapper);
}


key:默认生成缓存分区名::SimpleKey [](自动生成的key值)
value:默认使用jdk序列化机制,将序列化后的数据存到redis
默认过期时间:-1永不过期

  • 自定义key和过期时间
/**
* //代表当前方法返回结果需要缓存,若缓存中有,不调用方法,如果没有,调用方法最后将方法的结果放入缓存
* 放入category缓存分区中
* key若使用字符串加'',因为可接受SpEl表达式
*/
@Cacheable(value = {"category"},key ="#root.method.name" )
#1小时过期时间单位毫秒,雪崩?
spring.cache.redis.time-to-live=3600000
  • 修改序列化机制
@Configuration
@EnableCaching
public class MyCacheConfig {
@Bean
RedisCacheConfiguration redisCacheConfiguration() {
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
//修改序列化机制
config = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
config = config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
return config;
}
}
![Uploading file..._w2d070jab]()


1、之前配的过期时间失效 2、开启缓存注解改为这里配置,启动类上就不需要了
加上读取配置文件

//@EnableConfigurationProperties(CacheProperties.class)
@Configuration
@EnableCaching
public class MyCacheConfig {
@Bean
RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties) {
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
//修改序列化机制
config = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
config = config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
//因为用了自己的配置,默认配置中读取配置文件的内容就失效了
CacheProperties.Redis redisProperties = cacheProperties.getRedis();
if (redisProperties.getTimeToLive() != null) {
config = config.entryTtl(redisProperties.getTimeToLive());
}
if (redisProperties.getKeyPrefix() != null) {
config = config.prefixKeysWith(redisProperties.getKeyPrefix());
}
if (!redisProperties.isCacheNullValues()) {
config = config.disableCachingNullValues();
}
if (!redisProperties.isUseKeyPrefix()) {
config = config.disableKeyPrefix();
}
return config;
}
}

其他配置

#缓存前缀,是否开启
spring.cache.redis.key-prefix=CACHE_
spring.cache.redis.use-key-prefix=true
#缓存空值,可解决缓存穿透
spring.cache.redis.cache-null-values=true
  • 删除缓存
@CacheEvict(value = "category",key = "'getFirstLevelCategorys'")
  • 同时进行多个缓存操作
@Caching(evict = {
@CacheEvict(value = "category", key = "'getFirstLevelCategorys'"),
@CacheEvict(value = "category",key = "'getCatelogJsonPlus'")
})
  • 删除整个分区下所有的key
@CacheEvict(value = "category",allEntries = true)
  • 加本地锁
@Cacheable(value = {"category"}, key = "#root.method.name",sync = true)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值