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

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

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

瀏覽:87日期: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
相關文章:
主站蜘蛛池模板: 贵溪市| 阿勒泰市| 柏乡县| 中宁县| 江川县| 东港市| 武汉市| 射阳县| 诸暨市| 郯城县| 丽江市| 南充市| 渝中区| 克什克腾旗| 尤溪县| 长沙县| 大余县| 大宁县| 镇安县| 宁波市| 若尔盖县| 岳阳市| 民县| 江城| 和龙市| 眉山市| 郧西县| 菏泽市| 安图县| 磴口县| 扎兰屯市| 正安县| 黄龙县| 惠东县| 南溪县| 台中市| 蒙山县| 曲阳县| 靖远县| 舞钢市| 北流市|