Reputation: 5858
I am trying to do this.
I have a list of objects (Custom objects), I want to save them all in a single register in Redis, is it possible to save them as ajax somehow? I was reading about Jackson but I couldn't figure it how.
So far I only have this
@Autowired
private StringRedisTemplate redisTmpl;
And I can save like this
redisTmpl.opsForValue().set("foo", "bar");
Works pretty good, but instead of Bar , I want to save my list of objects (using this StringRedisTemplate
.
Any idea how to do it?
Or maybe using another way? But I need to save all the list in just one key.
Thanks
Upvotes: 2
Views: 21689
Reputation: 567
Using redisson you can do this:
ObjectMapper mapper = new ObjectMapper();
RList<MyObject> list = redissonCLient.getList("myKey");
list.add(mapper.writeValueAsString(new MyObject("test")));
The code above will save a Redis List in JSON format with the MyObjects values.
To retrieve the list you can do:
RList<MyObject> list = redissonCLient.getList("myKey");
List<MyObject> myObjects = mapper.readValue(list.toString(), new TypeReference<List<MyObject>>(){});
Upvotes: 0
Reputation: 10793
You can try Redisson as well. It supports many codecs like Jackson JSON
, Avro
, Smile
, CBOR
, MsgPack
, Kryo
, FST
, LZ4
, Snappy
and JDK Serialization
. It's very easy in use:
List<Object> list = ...
redisson.getBucket("yourKey").set(list);
// or use Redis list object
redisson.getList("yourKey").addAll(list);
Upvotes: 0
Reputation: 636
you should use spring support to convert your values to JSON like below example. It also convert your key to string directly.
<bean id="serializer" class="org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer">
<constructor-arg>
<value type="java.lang.Class">your.class.path.to.be.saved.in.redis</value>
</constructor-arg>
</bean>
<bean id="template" class="org.springframework.data.redis.core.RedisTemplate"
p:connection-factory-ref="redisConnectionFactory">
<property name="valueSerializer" ref="serializer"/>
<property name="keySerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
</property>
</bean>
Upvotes: 0
Reputation: 5858
I Found the way to do it....
To save all the list you can use jackson, on this way
ObjectMapper mapper = new ObjectMapper();
String jsonInString = mapper.writeValueAsString(myList);
And later you just save it on same way
redisTmpl.opsForValue().set("foo", jsonInString);
Upvotes: 5
Reputation: 3502
If you can serialize your object as JSON
, you can store it as string in redis. but for this you may need to create serializer/deserializer methods for your class.
Upvotes: 0