国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

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

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

瀏覽:119日期: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
相關文章:
主站蜘蛛池模板: 阿尔山市| 杭锦后旗| 永宁县| 鹤庆县| 沙湾县| 南岸区| 高邑县| 云阳县| 大姚县| 古交市| 利津县| 虹口区| 会昌县| 镇沅| 麻城市| 华坪县| 平顶山市| 白河县| 彰化县| 邻水| 宜兰县| 澄城县| 常宁市| 玉龙| 蓬莱市| 旌德县| 保德县| 寻甸| 哈密市| 河津市| 龙游县| 七台河市| 漳浦县| 怀柔区| 荆州市| 汕尾市| 淳化县| 海南省| 江津市| 汾阳市| 长宁县|