Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing different data using RedisTemplate (Spring)

Tags:

spring

redis

I'm using Spring's RedisTemplate to interface with Redis.

Currently the data I'm storing in Redis uses the OpsForHash operations because that's most appropriate for the data I am storing.

But now I want to add data of a different structure which is Key -> List

Should I therefore, have different instances of RedisTemplate in each of my daos (parameterised as required) but connecting to the same instance of Redis? Is that correct? Or should I have a shared instance of RedisTemplate which I can use for storing both Hash-Structured data and List structured data? If it's the latter how do I do that when I'm restricted by the Parameterisation of the instance? i.e. currently I have

Key (String) --> Map

And now I want to add

Key (String) --> List

Is that possible using a single RedisTemplate?

Thanks!

like image 925
Kash. Avatar asked Apr 13 '13 10:04

Kash.


People also ask

Is RedisTemplate thread safe?

Once configured, the template is thread-safe and can be reused across multiple instances. RedisTemplate uses a Java-based serializer for most of its operations.

What is RedisTemplate used for?

Performs automatic serialization/deserialization between the given objects and the underlying binary data in the Redis store. By default, it uses Java serialization for its objects (through JdkSerializationRedisSerializer ).

How Redis works in spring boot?

Redis supports data structures such as strings, hashes, lists, sets, and sorted sets with range queries. The Spring Data Redis framework makes it easy to write Spring applications that use the Redis Key-Value store by providing an abstraction to the data store.

What is opsForValue in Redis?

template.opsForValue().set(STRING_KEY_PREFIX + kvp.getKey(), kvp.getValue()); return kvp; We will use the RedisTemplate instance template opsForValue() method to get an instance of ValueOperations , which provides methods to execute operations performed on simple values (or Strings in Redis terminology).


1 Answers

Since your key type is String in both cases, you should be able to use the same instance of RedisTemplate, assuming you've parameterized RedisTemplate with the value type of your List. For example:

RedisTemplate<String, String> template;
// Hash Key/Value types can be anything as long as the proper serializers are set
HashOperations<String,String,Integer> hashOps = template.opsForHash();
hashOps.put("foo", "bar", 3);
// List value types are taken from RedisTemplate parameterization
ListOperations<String,String> listOps = template.opsForList();
listOps.leftPush("foolist", "bar");
like image 147
Jennifer Hickey Avatar answered Oct 03 '22 23:10

Jennifer Hickey