解决spring中redistemplate不能用通配符keys查出相应Key的问题
时间:2021-04-05 10:11:11|栏目:JAVA代码|点击: 次
有个业务中需要删除某个前缀的所有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());
栏 目:JAVA代码
本文标题:解决spring中redistemplate不能用通配符keys查出相应Key的问题
本文地址:http://www.codeinn.net/misctech/95063.html


阅读排行
- 1Java Swing组件BoxLayout布局用法示例
- 2java中-jar 与nohup的对比
- 3Java邮件发送程序(可以同时发给多个地址、可以带附件)
- 4Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type异常
- 5Java中自定义异常详解及实例代码
- 6深入理解Java中的克隆
- 7java读取excel文件的两种方法
- 8解析SpringSecurity+JWT认证流程实现
- 9spring boot里增加表单验证hibernate-validator并在freemarker模板里显示错误信息(推荐)
- 10深入解析java虚拟机




