使用@CacheEvict(value = “xxx”, allEntries = true)
导致redis报错:
nested exception is redis.clients.jedis.exceptions.JedisDataException: ERR unknow command ‘KEYS’;
优化方式:
注释此注解
然后在注解@CacheEvict的方法中加入批量清除缓存如下,用scan代替keys命令
@Autowired
private RedisTemplate redisTemplate;
public void deleteKeys(String xxx) {
//此处的xxx就是@CacheEvict(value = "xxx")这个,进行模糊匹配
String matchKey = xxx + "*";
Set<String> delKeys = new HashSet<>();
try {
redisTemplate.execute((RedisCallback<Set<String>>) backs -> {
Cursor<byte[]> cursor = backs.scan(new ScanOptions.ScanOptionsBuilder().match(matchKey ).count(Integer.MAX_VALUE).build());
while (cursor.hasNext()) {
delKeys.add(new String(cursor.next()));
}
if (ArrayUtil.isNotEmptyCollection(delKeys)) {
redisTemplate.delete(delKeys);
}
return delKeys;
});
} catch (Throwable e) {
e.printStackTrace();
}
}
多说一句:
@CacheEvict(value = “xxx”, key = “‘abc’+#user.id”)
@CacheEvict此注解如果指定了key,不会引发KEYS命令,不用多加处理