如何使用 redis 模板从 Redis 获取所有密钥 [英] How to get all Keys from Redis using redis template
问题描述
我已经被这个问题困扰了很长时间.我想使用 redis 模板从 redis 获取密钥.我试过 this.redistemplate.keys("*");但这并没有得到任何东西.即使使用模式它也不起作用.
I have been stuck with this problem with quite some time.I want to get keys from redis using redis template. I tried this.redistemplate.keys("*"); but this doesn't fetch anything. Even with the pattern it doesn't work.
你能告诉我什么是最好的解决方案吗.
Can you please advise on what is the best solution to this.
推荐答案
我刚刚整理了答案,我们已经在这里看到了.
I just consolidated the answers, we have seen here.
这里有两种从Redis获取key的方法,当我们使用RedisTemplate时.
Here are the two ways of getting keys from Redis, when we use RedisTemplate.
1.直接来自RedisTemplate
Set<String> redisKeys = template.keys("samplekey*"));
// Store the keys in a List
List<String> keysList = new ArrayList<>();
Iterator<String> it = redisKeys.iterator();
while (it.hasNext()) {
String data = it.next();
keysList.add(data);
}
注意:您应该在 bean 中使用 StringRedisSerializer 配置 redisTemplate
Note: You should have configured redisTemplate with StringRedisSerializer in your bean
如果你使用基于 Java 的 bean 配置
redisTemplate.setDefaultSerializer(new StringRedisSerializer());
如果你使用基于 spring.xml 的 bean 配置
<bean id="stringRedisSerializer" class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
<!-- redis template definition -->
<bean
id="redisTemplate"
class="org.springframework.data.redis.core.RedisTemplate"
p:connection-factory-ref="jedisConnectionFactory"
p:keySerializer-ref="stringRedisSerializer"
/>
2.来自 JedisConnectionFactory
RedisConnection redisConnection = template.getConnectionFactory().getConnection();
Set<byte[]> redisKeys = redisConnection.keys("samplekey*".getBytes());
List<String> keysList = new ArrayList<>();
Iterator<byte[]> it = redisKeys.iterator();
while (it.hasNext()) {
byte[] data = (byte[]) it.next();
keysList.add(new String(data, 0, data.length));
}
redisConnection.close();
如果您不明确关闭此连接,您将遇到底层 jedis 连接池耗尽的情况,如 https 中所述://stackoverflow.com/a/36641934/3884173.
If you don't close this connection explicitly, you will run into an exhaustion of the underlying jedis connection pool as said in https://stackoverflow.com/a/36641934/3884173.
这篇关于如何使用 redis 模板从 Redis 获取所有密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!