167、缓存-SpringCache-简介
1)SpringCache官网
2)简介
3)基础概念
168、缓存-SpringCache-整合&体验@Cacheable
1)引入依赖
<!-- 引入redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<exclusions>
<exclusion>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
2)写配置
2.1)自动配置了那些
2.2)配置使用Redis作为缓存
3)测试使用缓存
- @Cacheable: Triggers cache population.
触发将数据保存到缓存的操作 - @CacheEvict: Triggers cache eviction.
触发将数据从缓存删除的操作 - @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.
在类级别共享缓存相同的配置
3.1)注解开启缓存
3.2)方法添加缓存注解
169、缓存-SpringCache-@Cacheable细节设置
1)默认行为
- 如果缓存中有,方法不调用
- key默认自动生成;缓存的名字::SimpleKey[]【自动生成的key值】
- 缓存的value的值。默认使用jdk序列化机制,将序列化后的数据存到redis
- 默认ttl时间 -1; 永不过期
2)自定义
- 指定生成缓存中使用的key,key属性指定,接受一个SpEL
https://docs.spring.io/spring-framework/docs/5.1.19.RELEASE/spring-framework-reference/integration.html#cache-spel-context - 指定缓存数据的存活时间,配置文件中修改ttl
# 配置过期时间 单位为毫秒
spring.cache.redis.time-to-live=600000
- 将数据保存为json格式
170、缓存-SpringCache-自定义缓存配置
1)原理分析
2)让ConfigurationProperties配置生效
3)配置自定义序列化方法
171、缓存-SpringCache-@CacheEvict
属于失效模式
批量删除缓存的方法
172、缓存-SpringCache-原理与不足
1)、读模式
缓存穿透:查询一个null数据。解决方案:缓存空数据
缓存击穿:大量并发进来同时查询一个正好过期的数据。解决方案:加锁 ? 默认是无加锁的;使用sync = true来解决击穿问题
缓存雪崩:大量的key同时过期。解决:加随机时间。加上过期时间
2)、写模式:(缓存与数据库一致)
1)、读写加锁。
2)、引入Canal,感知到MySQL的更新去更新Redis
3)、读多写多,直接去数据库查询就行
总结:
常规数据(读多写少,即时性,一致性要求不高的数据,完全可以使用Spring-Cache):写模式(只要缓存的数据有过期时间就足够了)
特殊数据:特殊设计
原理:
CacheManager(RedisCacheManager)->Cache(RedisCache)->Cache负责缓存的读写