成人在线亚洲_国产日韩视频一区二区三区_久久久国产精品_99国内精品久久久久久久

您的位置:首頁(yè)技術(shù)文章
文章詳情頁(yè)

解決spring中redistemplate不能用通配符keys查出相應(yīng)Key的問(wèn)題

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

有個(gè)業(yè)務(wù)中需要?jiǎng)h除某個(gè)前綴的所有Redis緩存,于是用RedisTemplate的keys方法先查出所有合適的key,再遍歷刪除。

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

解決問(wèn)題:

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ù)器阻塞,無(wú)坑!完美解決方案

先來(lái)鄙視下博客上很多人不懂瞎幾把亂說(shuō)還有大量轉(zhuǎn)載誤導(dǎo)群眾,本文原創(chuàng)親自驗(yàn)證方案。

話不多說(shuō)先上代碼,拿走即用。

long start = System.currentTimeMillis(); //需要匹配的key String patternKey = 'pay:*'; ScanOptions options = ScanOptions.scanOptions() //這里指定每次掃描key的數(shù)量(很多博客瞎說(shuō)要指定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的問(wèn)題就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。

標(biāo)簽: Spring
相關(guān)文章: