Search code examples
redisspring-dataspring-data-redis

how to get both keys and values when using redis's 'keys' command


I want to get both keys and values . Now I'm doing it like this:

Set<String> keys = redisTemplate.keys("Tom*");
if (keys != null) {

   //get them one by one
   for (String key : keys) {
      String value = redisTemplate.opsForValue().get(key);
   }
}

first, I have to get all the keys which starts with "abc". second, I get values one by one.

Can I get both keys and values at one time?

UPDATE:

Thank soveran.
I have some properties associated to each user:

1)Tom.loginTimes=3  
2)Tom.tradeMoneyCount=100 

Before I define two separated keys: Tom.loginTimes and Tom.tradeMoneyCount. Now I think I should use hmset:

10.75.201.3:63790> hmset Tom loginTimes 3 tradeMoneyCount 100
OK
10.75.201.3:63790> hgetall Tom
1) "loginTimes"
2) "3"
3) "tradeMoneyCount"
4) "100"

Thanks.


Solution

  • hashes is the right way to do it.

    As for the keys command, it was added to redis for debug purposes and never meant to be used in production. Here is a warning from redis docs for keys command:

    Warning: consider KEYS as a command that should only be used in production environments with extreme care. It may ruin performance when it is executed against large databases. This command is intended for debugging and special operations, such as changing your keyspace layout. Don't use KEYS in your regular application code. If you're looking for a way to find keys in a subset of your keyspace, consider using SCAN or sets.