I am able to add and get a particular user object from Redis I am adding object like this:
private static final String USER_PREFIX = ":USER:";
public void addUserToRedis(String serverName,User user) {
redisTemplate.opsForHash().put(serverName + USER_PREFIX + user.getId(),
Integer.toString(user.getId()),user);
}
If a userId is 100 I am able to get by key: SERVER1:USER:100
Now I want to retrieve all Users as Map<String,List<User>>
,
For example, get all users by this key SERVER1:USER:
Is it possible ? Or I need to modify my addUserToRedis method? Please suggest me.
3
Answers
Finally I came up with this solution with wildcard search and avoiding KEYS, and here is my complete method:
I would recommend not using the "KEYS" command in production as this can severely impact REDIS latencies (can even bring down the cluster if you have a large number of keys stored)
Instead, you would want to use a different command than plain GET/SET.
It would be better if you use a Sets or Hashes
Using sets you can simply add your users to server keys and get the entire list of users on a server.
If you really need a map of
< server, list < users > >
you can use hashes with stringified user data and then convert it to actualUser
POJO at application layerAlso do note that keeping this much big data into a single key is not an ideal thing to do.
i dont use java but here’s how to use SCAN