问题
使用Springboot Cache,缓存用的Redis,代码如下:
@CacheEvict(value="user", allEntries = true)
public void addUser(User user) {
this.users.put(user.getId(), user);
}
执行上面代码时报了如下错误:
ERR unknown command `KEYS`
原因
Springboot CacheEvict的默认实现,如果allEntries = true,则使用Redis KEYS命令来清除缓存。KEYS命令可能会带来性能问题,因此生产环境可能会禁用KEYS命令,结果造成异常。
解决方案
网上有许多相关文章,多是查看Springboot代码,然后自己进行扩展,改用Scan命令去修复。其实新版的Springboot(比如最新的3.7.1)已经提供了Scan实现,自己配置一下就行了。
@Bean
public CacheManager cacheManager(RedisConnectionFactory connectionFactory) {
/* 默认配置, 默认超时时间为30s */
RedisCacheConfiguration defaultCacheConfig =RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration
.ofMinutes(Long.valueOf(10))).disableCachingNullValues();
RedisCacheManager cacheManager = RedisCacheManager.builder(RedisCacheWriter.lockingRedisCacheWriter
(connectionFactory,
BatchStrategies.scan(1000))).cacheDefaults(defaultCacheConfig).transactionAware().build();
return cacheManager;
}