Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring RedisTemplate : use same key with multiple RedisTemplate to store different values

I am new to Redis and want to implement it with my existing spring application.

My question is to use different redisTemplate with same keys to store different types of values.

For e.g.

I have redisTemplate1 and redisTemplate2 beans defined in spring, like.

<bean id="redisTemplate1" class ="org.springframework.data.redis.core.RedisTemplate" p:connection-factory-ref ="connectionFactory" />

<bean id="redisTemplate2" class ="org.springframework.data.redis.core.RedisTemplate" p:connection-factory-ref ="connectionFactory" />

In java file to my service, I have created two different data structure using these two redis templates.

@Autowired
@Qualifier(value = "redisTemplate1")
private RedisTemplate<String, Student>       redisTemplate1;

@Autowired
@Qualifier(value = "redisTemplate2")
private RedisTemplate<String, Address>       redisTemplate2;

And, using following pattern to store data.

redisTemplate1.opsForHash().put("KEY1", student.getId(), student);
redisTemplate2.opsForHash().put("KEY1", address.getId(), address);

The case is, I have primary keys starting with 1 for each table. So 1 is there a primary key of Student as well as of Address.

I am using line below to get Student back from data-store.

(Student) redisTemplate1.opsForHash().get("KEY1", 1);

But, unfortunately it generates an exception.

java.lang.ClassCastException: com.redis.model.Address cannot be cast to com.redis.model.Student

So, my questions are,

  • Is it possible to use multiple redis templates ?
  • If yes, can I use same key (unique for each template) to store different types of data and access the same data stored using that template and key ?
  • If not, what are the alternative to perform same operation ?

Thanks in advance.

like image 419
Ashvin Kanani Avatar asked Nov 01 '22 02:11

Ashvin Kanani


1 Answers

Actually Redis is a key/value store and if you use the same key for the same store you just override the old value with new one. And it doesn't matter how much RedisTemplates (or even connectionFactorys) you have, if the real Redis server is the same.

Now how to help you with your task:

You should have different kyes for different domain objects: e.g. students, addresses. Since you are going to store domain objects with their own keys it looks like Map value is for you. I mean under key students a map of Students should be stored ,and the same for Addresses.

However you, actually, do it, but you use the same key for both domains. So, the answer for you: that's because you are using the same Redis from both RedisTemplates.

like image 116
Artem Bilan Avatar answered Nov 15 '22 05:11

Artem Bilan