spring redis 如何實現(xiàn)模糊查找key
更新時間:2021年08月10日 15:52:03 作者:路過君_P
這篇文章主要介紹了spring redis 如何實現(xiàn)模糊查找key的操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
spring redis 模糊查找key
用法
Set<String> keySet = stringRedisTemplate.keys("keyprefix:"+"*");
- 需要使用StringRedisTemplate,或自定義keySerializer為StringRedisSerializer的redisTemplate
- redis里模糊查詢key允許使用的通配符:
* 任意多個字符
? 單個字符
[] 括號內(nèi)的某1個字符
源碼
org.springframework.data.redis.core.RedisTemplate
public 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
- 基于游標迭代分次遍歷key,不會一次性掃描所有key導致性能消耗過大,減少服務(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);
}
});
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中用戶收聽歷史被清空"
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Spring與Struts整合之讓Spring管理控制器操作示例
這篇文章主要介紹了Spring與Struts整合之讓Spring管理控制器操作,結(jié)合實例形式詳細分析了Spring管理控制器相關(guān)配置、接口實現(xiàn)與使用技巧,需要的朋友可以參考下2020-01-01
關(guān)于Filter中獲取請求體body后再次讀取的問題
這篇文章主要介紹了關(guān)于Filter中獲取請求體body后再次讀取的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-03-03
SpringBoot+hutool實現(xiàn)圖片驗證碼
本文主要介紹了SpringBoot+hutool實現(xiàn)圖片驗證碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-08-08

