1. 程式人生 > 程式設計 >解決spring中redistemplate不能用萬用字元keys查出相應Key的問題

解決spring中redistemplate不能用萬用字元keys查出相應Key的問題

有個業務中需要刪除某個字首的所有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伺服器阻塞,無坑!完美解決方案

先來鄙視下部落格上很多人不懂瞎幾把亂說還有大量轉載誤導群眾,本文原創親自驗證方案。

話不多說先上程式碼,拿走即用。

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的問題就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。