解決spring中redistemplate不能用通配符keys查出相應(yīng)Key的問題
有個業(yè)務(wù)中需要刪除某個前綴的所有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服務(wù)器阻塞,無坑!完美解決方案
先來鄙視下博客上很多人不懂瞎幾把亂說還有大量轉(zhuǎn)載誤導(dǎo)群眾,本文原創(chuàng)親自驗證方案。
話不多說先上代碼,拿走即用。
long start = System.currentTimeMillis();
//需要匹配的key
String patternKey = "pay:*";
ScanOptions options = ScanOptions.scanOptions()
//這里指定每次掃描key的數(shù)量(很多博客瞎說要指定Integer.MAX_VALUE,這樣的話跟 keys有什么區(qū)別?)
.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());
}
//切記這里一定要關(guān)閉,否則會耗盡連接數(shù)。報Cannot get Jedis connection; nested exception is redis.clients.jedis.exceptions.JedisException: Could not get a
cursor.close();
log.info("scan掃描共耗時:{} ms key數(shù)量:{}",System.currentTimeMillis()-start,result.size());
以上這篇解決spring中redistemplate不能用通配符keys查出相應(yīng)Key的問題就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Mybatis執(zhí)行Update返回行數(shù)為負數(shù)的問題
這篇文章主要介紹了Mybatis執(zhí)行Update返回行數(shù)為負數(shù)的問題,具有很好的參考價值,希望大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-12-12
Java根據(jù)開始時間和結(jié)束時間及周幾計算日期的示例代碼
在Java 7中,java.time包不存在,所以我們需要使用java.util.Calendar和java.util.Date類來實現(xiàn)類似的功能,這篇文章主要介紹了Java根據(jù)開始時間和結(jié)束時間及周幾計算出日期的示例代碼,需要的朋友可以參考下2024-06-06
淺談Java中的final關(guān)鍵字與C#中的const, readonly關(guān)鍵字
下面小編就為大家?guī)硪黄獪\談Java中的final關(guān)鍵字與C#中的const, readonly關(guān)鍵字。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-10-10
SpringBoot配置動態(tài)數(shù)據(jù)源的實戰(zhàn)詳解
Spring對數(shù)據(jù)源的管理類似于策略模式,不懂策略模式也沒關(guān)系,其實就是有一個全局的鍵值對,類型是Map<String, DataSource>,當JDBC操作數(shù)據(jù)庫之時,會根據(jù)不同的key值選擇不同的數(shù)據(jù)源,本文介紹了SpringBoot配置動態(tài)數(shù)據(jù)源的方法,需要的朋友可以參考下2024-08-08
mybatis新增到數(shù)據(jù)庫后返回當前ID問題
這篇文章主要介紹了mybatis新增到數(shù)據(jù)庫后返回當前ID問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-08-08

