spring redis 如何實(shí)現(xiàn)模糊查找key
Set<String> keySet = stringRedisTemplate.keys('keyprefix:'+'*'); 需要使用StringRedisTemplate,或自定義keySerializer為StringRedisSerializer的redisTemplate redis里模糊查詢key允許使用的通配符:
* 任意多個(gè)字符
? 單個(gè)字符
[] 括號(hào)內(nèi)的某1個(gè)字符
源碼org.springframework.data.redis.core.RedisTemplatepublic Set<K> keys(K pattern) { byte[] rawKey = rawKey(pattern); Set<byte[]> rawKeys = execute(connection -> connection.keys(rawKey), true); return keySerializer != null ? SerializationUtils.deserialize(rawKeys, keySerializer) : (Set<K>) rawKeys;}改善 Redis2.8以后可以使用scan獲取key 基于游標(biāo)迭代分次遍歷key,不會(huì)一次性掃描所有key導(dǎo)致性能消耗過大,減少服務(wù)器阻塞
可以通過count參數(shù)設(shè)置掃描的范圍
Set<String> keys = new LinkedHashSet<>();stringRedisTemplate.execute((RedisConnection connection) -> { try (Cursor<byte[]> cursor = connection.scan( ScanOptions.scanOptions() .count(Long.MAX_VALUE) .match(pattern) .build() )) {cursor.forEachRemaining(item -> { keys.add(RedisSerializer.string().deserialize(item));});return null; } catch (Exception e) {throw new RuntimeException(e); }});
Reids SCAN命令官方文檔
redis-redisTemplate模糊匹配刪除String key = 'noteUserListenedPoi:*'; redisTemplate.delete(key); LOGGER.info('redis中用戶收聽歷史被清空');
后來測試發(fā)現(xiàn)模糊查詢是可以用的, 刪除改成
Set<String> keys = redisTemplate.keys('noteUserListenedPoi:' + '*'); redisTemplate.delete(keys); LOGGER.info('{}, redis中用戶收聽歷史被清空'
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. ASP 信息提示函數(shù)并作返回或者轉(zhuǎn)向2. windows服務(wù)器使用IIS時(shí)thinkphp搜索中文無效問題3. PHP設(shè)計(jì)模式中工廠模式深入詳解4. 淺談python出錯(cuò)時(shí)traceback的解讀5. .NET中l(wèi)ambda表達(dá)式合并問題及解決方法6. Python importlib動(dòng)態(tài)導(dǎo)入模塊實(shí)現(xiàn)代碼7. python matplotlib:plt.scatter() 大小和顏色參數(shù)詳解8. Ajax實(shí)現(xiàn)表格中信息不刷新頁面進(jìn)行更新數(shù)據(jù)9. 利用promise及參數(shù)解構(gòu)封裝ajax請(qǐng)求的方法10. JSP數(shù)據(jù)交互實(shí)現(xiàn)過程解析
