您的位置:首頁技術文章
文章詳情頁

解決spring中redistemplate不能用通配符keys查出相應Key的問題

瀏覽:58日期:2023-07-31 13:09:23

有個業務中需要刪除某個前綴的所有Redis緩存,于是用RedisTemplate的keys方法先查出所有合適的key,再遍歷刪除。

但是在keys(patten+'*')時每次取出的都為空。

解決問題:

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>

補充知識: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());

以上這篇解決spring中redistemplate不能用通配符keys查出相應Key的問題就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。

標簽: Spring
相關文章:
国产综合久久一区二区三区