解決spring中redistemplate不能用通配符keys查出相應(yīng)Key的問題
有個(gè)業(yè)務(wù)中需要?jiǎng)h除某個(gè)前綴的所有Redis緩存,于是用RedisTemplate的keys方法先查出所有合適的key,再遍歷刪除。
但是在keys(patten+'*')時(shí)每次取出的都為空。
解決問題:
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ù)器阻塞,無坑!完美解決方案
先來鄙視下博客上很多人不懂瞎幾把亂說還有大量轉(zhuǎn)載誤導(dǎo)群眾,本文原創(chuàng)親自驗(yàn)證方案。
話不多說先上代碼,拿走即用。
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)閉,否則會(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的問題就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. IntelliJ IDEA導(dǎo)入jar包的方法2. js實(shí)現(xiàn)貪吃蛇小游戲(加墻)3. 基于Go和PHP語言實(shí)現(xiàn)爬樓梯算法的思路詳解4. JAMon(Java Application Monitor)備忘記5. JVM之class文件結(jié)構(gòu)6. Html5播放器實(shí)現(xiàn)倍速播放的方法示例7. asp知識(shí)整理筆記4(問答模式)8. Python中Anaconda3 安裝gdal庫的方法9. JSP實(shí)現(xiàn)百萬富翁猜數(shù)字游戲10. python對(duì)批量WAV音頻進(jìn)行等長分割的方法實(shí)現(xiàn)
