问题描述
我一直困扰这个问题很长时间,我想使用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.
当我们使用RedisTemplate时,有两种从Redis获取密钥的方法.
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
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获取所有密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!