解決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. PHP正則表達(dá)式函數(shù)preg_replace用法實(shí)例分析2. 一個(gè) 2 年 Android 開(kāi)發(fā)者的 18 條忠告3. vue使用moment如何將時(shí)間戳轉(zhuǎn)為標(biāo)準(zhǔn)日期時(shí)間格式4. js select支持手動(dòng)輸入功能實(shí)現(xiàn)代碼5. Android 實(shí)現(xiàn)徹底退出自己APP 并殺掉所有相關(guān)的進(jìn)程6. Android studio 解決logcat無(wú)過(guò)濾工具欄的操作7. 什么是Python變量作用域8. vue-drag-chart 拖動(dòng)/縮放圖表組件的實(shí)例代碼9. Spring的異常重試框架Spring Retry簡(jiǎn)單配置操作10. Vue實(shí)現(xiàn)仿iPhone懸浮球的示例代碼
