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
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 redisKeys = template.keys("samplekey*"));
// Store the keys in a List
List keysList = new ArrayList<>();
Iterator 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
2. From JedisConnectionFactory
RedisConnection redisConnection = template.getConnectionFactory().getConnection();
Set redisKeys = redisConnection.keys("samplekey*".getBytes());
List keysList = new ArrayList<>();
Iterator 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.