解決spring中redistemplate不能用通配符keys查出相應(yīng)Key的問(wèn)題
有個(gè)業(yè)務(wù)中需要?jiǎng)h除某個(gè)前綴的所有Redis緩存,于是用RedisTemplate的keys方法先查出所有合適的key,再遍歷刪除。
但是在keys(patten+'*')時(shí)每次取出的都為空。
解決問(wèn)題:
spring中redis配置中,引入StringRedisTemplate而不是RedisTemplate,StringRedisTemplate本身繼承自RedisTemplate,
即
<bean class='org.springframework.data.redis.core.RedisTemplate'><property name='connectionFactory' ref='connectionFactory' /></bean>
改為
<bean class='org.springframework.data.redis.core.StringRedisTemplate'><property name='connectionFactory' ref='connectionFactory' /></bean>
補(bǔ)充知識(shí):RedisTemplate使用SCAN命令掃描key替代KEYS避免redis服務(wù)器阻塞,無(wú)坑!完美解決方案
先來(lái)鄙視下博客上很多人不懂瞎幾把亂說(shuō)還有大量轉(zhuǎn)載誤導(dǎo)群眾,本文原創(chuàng)親自驗(yàn)證方案。
話不多說(shuō)先上代碼,拿走即用。
long start = System.currentTimeMillis(); //需要匹配的key String patternKey = 'pay:*'; ScanOptions options = ScanOptions.scanOptions() //這里指定每次掃描key的數(shù)量(很多博客瞎說(shuō)要指定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)閉,否則會(huì)耗盡連接數(shù)。報(bào)Cannot get Jedis connection; nested exception is redis.clients.jedis.exceptions.JedisException: Could not get a cursor.close(); log.info('scan掃描共耗時(shí):{} ms key數(shù)量:{}',System.currentTimeMillis()-start,result.size());
以上這篇解決spring中redistemplate不能用通配符keys查出相應(yīng)Key的問(wèn)題就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. Python使用oslo.vmware管理ESXI虛擬機(jī)的示例參考2. 淺談django不使用restframework自定義接口與使用的區(qū)別3. 如何理解SpringMVC4. 解決idea web項(xiàng)目中out目錄更新不同步問(wèn)題5. intellij idea使用git stash暫存一次提交的操作6. 關(guān)于Spring自定義XML schema 擴(kuò)展的問(wèn)題(Spring面試高頻題)7. 通過(guò)實(shí)例解析Python文件操作實(shí)現(xiàn)步驟8. 關(guān)于PHP程序員解決問(wèn)題的能力9. Spring Bean管理注解方式代碼實(shí)例10. Jsp servlet驗(yàn)證碼工具類分享
