解决spring中redistemplate不能用通配符keys查出相应Key的问题

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

解决spring中redistemplate不能用通配符keys查出相应Key的问题

大树叶   2020-11-24 我要评论

有个业务中需要删除某个前缀的所有Redis缓存,于是用RedisTemplate的keys方法先查出所有合适的key,再遍历删除。

但是在keys(patten+"*")时每次取出的都为空。

解决问题:

spring中redis配置中,引入StringRedisTemplate而不是RedisTemplate,StringRedisTemplate本身继承自RedisTemplate,

<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="connectionFactory" />
</bean>

改为

<bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">
<property name="connectionFactory" ref="connectionFactory" />
</bean>

补充知识:RedisTemplate使用SCAN命令扫描key替代KEYS避免redis服务器阻塞,无坑!完美解决方案

先来鄙视下博客上很多人不懂瞎几把乱说还有大量转载误导群众,本文原创亲自验证方案。

话不多说先上代码,拿走即用。

long start = System.currentTimeMillis();
 //需要匹配的key
 String patternKey = "pay:*";
 ScanOptions options = ScanOptions.scanOptions()
  //这里指定每次扫描key的数量(很多博客瞎说要指定Integer.MAX_VALUE,这样的话跟 keys有什么区别?)
  .count(10000)
  .match(patternKey).build();
 RedisSerializer<String> redisSerializer = (RedisSerializer<String>) redisTemplate.getKeySerializer();
 Cursor cursor = (Cursor) redisTemplate.executeWithStickyConnection(redisConnection -> new ConvertingCursor<>(redisConnection.scan(options), redisSerializer::deserialize));
 List<String> result = new ArrayList<>();
 while(cursor.hasNext()){
  result.add(cursor.next().toString());
 }
 //切记这里一定要关闭,否则会耗尽连接数。报Cannot get Jedis connection; nested exception is redis.clients.jedis.exceptions.JedisException: Could not get a 
 cursor.close();
 log.info("scan扫描共耗时:{} ms key数量:{}",System.currentTimeMillis()-start,result.size());

以上这篇解决spring中redistemplate不能用通配符keys查出相应Key的问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们