优化 Infra 接入 Redisson
概要
Redisson 提供9大功能特色
- 框架集成 Spring Session/Cache/Quarkus …
- 支持 codecs MsgPack/CBOR/Jackson JSON …
- 分布式锁 Lock/RedLock …
- 分布式 Java集合/对象/Id generator/Bloom filter
- 支持 Redis 集群/哨兵/主从/单节点
- And so on …
接入 Redisson
提高接口响应速度,缓存接口响应接入 Spring Cache. 接入 Codec msgpack, 更高性能的编码解码。
代码展示
版本匹配
redisson-spring-data-2x 适配 Spring Boot 2.x.y
上 https://mvnrepository.com/ 查看具体依赖明细。
对应 Spring Boot 2.6.13, 即引入依赖 implementation 'org.redisson:redisson-spring-boot-starter:3.17.1'
// 读取 spring.redis和spring.redis.redisson 前缀配置
@EnableConfigurationProperties({RedissonProperties.class, RedisProperties.class})
org.redisson.spring.starter.RedissonAutoConfiguration
msgpack 更快更小
Codec 引入依赖 implementation 'org.msgpack:jackson-dataformat-msgpack:0.9.3'
MsgPackJacksonCodec 内 ObjectMapper 默认没有 registerModule java.time 序列化和反序列化
使用 Long 时间戳(性能好) 避开这个问题。
默认 ObjectMapper 设置在 org.redisson.codec.JsonJacksonCodec#init
application.yml 追加
---
spring.redis.redisson.file: classpath:redisson.yml
redisson.yml
singleServerConfig:
idleConnectionTimeout: 10000
connectTimeout: 10000
timeout: 3000
retryAttempts: 3
retryInterval: 1500
password: null
subscriptionsPerConnection: 5
clientName: null
address: "redis://192.168.1.168:6379"
subscriptionConnectionMinimumIdleSize: 1
subscriptionConnectionPoolSize: 50
connectionMinimumIdleSize: 32
connectionPoolSize: 64
database: 8
dnsMonitoringInterval: 5000
threads: 0
nettyThreads: 0
codec: !<org.redisson.codec.MsgPackJacksonCodec> {} # 设定codec为 MsgPack
transportMode: "NIO"
RedissonConfig
@Configuration
@EnableCaching
public class RedissonConfig {
@Bean
public CacheManager cacheManager(RedissonClient redissonClient) {
return new RedissonSpringCacheManager(redissonClient, "classpath:/cache-config.yml");
}
}
cache-config.yml
AccountService:
ttl: 900000
maxIdleTime: 720000
Service 调整
@CacheConfig(cacheNames = AccountService.CACHE_NAME) // 缓存领域名称
public class AccountServiceImpl implements AccountService {...}
@Override
@CacheEvict(allEntries = true) // 删除 cacheNames 下,所有缓存
public void removeAllAccount() {...}
@Cacheable(key = "#root.targetClass + '-' + #accountLoginQry.userName") // 加入缓存
public Account accountLogin(AccountLoginQry accountLoginQry) {...}
@CacheEvict(key = "#root.targetClass + '-' + #p0") // 删除缓存
public void accountLogout(String userName) {...}
说明
注意缓存操作数据一致性,保障 加入/删除/更新 缓存key是同一个。
cacheNames = AccountService.CACHE_NAME 某个领域设定的缓存命名空间,配置 cache-config.yml 防止缓存雪崩。
方法内有异常抛出则不进行缓存操作(添加缓存/清除缓存)
缓存设置 Cacheable
先查找是否有缓存,有就返回,后执行方法体,缓存返回值
解决缓存击穿 sync = true
缓存清除 CacheEvict
默认方法成功执行才会清除缓存
beforeInvocation 方法调用之前就清除缓存
allEntries 表示操作指定缓存空间所有缓存
condition = "判断条件" 条件判断成立执行
缓存更新 CachePut
不查找是否有缓存,直接执行方法,然后缓存
默认缓存空值,解决缓存穿透