Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

spring - How to get all Keys from Redis using redis template

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I just consolidated the answers, we have seen here.

Here are the two ways of getting keys from Redis, when we use RedisTemplate.

1. Directly from 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);
}

Note: You should have configured redisTemplate with StringRedisSerializer in your bean

If you use java based bean configuration

redisTemplate.setDefaultSerializer(new StringRedisSerializer());

If you use spring.xml based bean configuration

<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. From 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();

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...