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.
try:
Avoid to use
keys
command. It may ruin performance when it is executed against large databases.You should use
scan
command instead. Here is how you can do it:or do it much simplier with Redisson Redis Java client:
Try
redisTemplate.setKeySerializer(new StringRedisSerializer());
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
Note: You should have configured redisTemplate with StringRedisSerializer in your bean
If you use java based bean configuration
If you use spring.xml based bean configuration
2. From JedisConnectionFactory
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.
I was using
redisTemplate.keys()
, but it was not working. So I used jedis, it worked. The following is the code that I used.It did work, but seems not recommended? Because we can't use Keys command in production. I assume
RedisTemplate.getConnectionFactory().getConnection().keys
is calling redis Keys command. What are the alternatives?