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,
Thanks in advance.
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 RedisTemplate
s (or even connectionFactory
s) 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 Student
s should be stored ,and the same for Address
es.
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 RedisTemplate
s.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With