spring redis 如何实现模糊查找key
Set<String> keySet = stringRedisTemplate.keys('keyprefix:'+'*'); 需要使用StringRedisTemplate,或自定义keySerializer为StringRedisSerializer的redisTemplate redis里模糊查询key允许使用的通配符:
* 任意多个字符
? 单个字符
[] 括号内的某1个字符
源码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 基于游标迭代分次遍历key,不会一次性扫描所有key导致性能消耗过大,减少服务器阻塞
可以通过count参数设置扫描的范围
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中用户收听历史被清空');
后来测试发现模糊查询是可以用的, 删除改成
Set<String> keys = redisTemplate.keys('noteUserListenedPoi:' + '*'); redisTemplate.delete(keys); LOGGER.info('{}, redis中用户收听历史被清空'
以上为个人经验,希望能给大家一个参考,也希望大家多多支持好吧啦网。
相关文章:
