Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all Keys from Redis using redis template

Tags:

spring

redis

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.

like image 424
user1744099 Avatar asked Sep 30 '13 15:09

user1744099


People also ask

How do I get all Redis keys?

To list the keys in the Redis data store, use the KEYS command followed by a specific pattern. Redis will search the keys for all the keys matching the specified pattern. In our example, we can use an asterisk (*) to match all the keys in the data store to get all the keys.

What is the use of Redis template?

To support various operations on different datatypes, RedisTemplate provides operation classes like ValueOperations , ListOperations , SetOperations , HashOperations , StreamOperations , etc. For hash-related operations, which we'll use to store data in our Redis server, we'll use the HashOperations class.

Which command is used to obtain all the keys in a database?

The Redis KEYS command returns all the keys in the database that match a pattern (or all the keys in the key space). Similar commands for fetching all the fields stored in a hash is HGETALL and for all fetching the members of a SMEMBERS. The keys in Redis themselves are stored in a dictionary (aka a hash table).

How get data from Redis?

Reading Data from Redis To retrieve a key with a string value, use the GET command. If a value does not exist for this key, GET replies with a nil. Since GET only works with string values, you need the LRANGE command to get list values. “0” in the example above specifies the start index of the list and “-1” the end.


2 Answers

Try

import org.springframework.data.redis.core.RedisTemplate;
import org.apache.commons.collections.CollectionUtils;

String key = "example*";
Set keys = redisTemplate.keys(key); 
if (CollectionUtils.isEmpty(keys)) return null;
List list = redisTemplate.opsForValue().multiGet(keys);
like image 186
Felipe Yudi Avatar answered Sep 19 '22 03:09

Felipe Yudi


Try redisTemplate.setKeySerializer(new StringRedisSerializer());

like image 34
dturanski Avatar answered Sep 18 '22 03:09

dturanski