I am trying to store Arraylist values which coming from DB to Redis Client . But Redis have only Key/Value methods the Key/Value must be String format. How can i store Key as String and Values As Arraylist.
5 Answers
But Redis have only Key/Value methods the Key/Value must be String format
Redis actually has very good support for storing values as lists, if that's what you want to do. Do that, if you want to do any sort of list operations on the value.
If you just want to store the list and retrieve it as a whole, then you want to just serialize it into a string prior to storing in Redis. In that case, encode the list as a JSON string (or any other serializing format) and store that in Redis. Then just GET it and deserialize when you want it back.
Comments
YOu have to use the Map to store data with keys and values
Map<String, ArrayList<String>> map = new Map<String, ArrayList<String>>();
ArrayList<String> a= new ArrayList<String>();
a.add("Ganesh");
map.put("Name", a);
2 Comments
You can use a set for this
Add members to the set individually, or in an array in redis-cli like so:
sadd my_new_set a b c d e f g
Comments
You can easily do this with Redis based framework - Redisson. It offers wrapped collections like java.util.List, java.util.Set, java.util.Map and many more.
Here is an example for List:
Config config = ...
RedissonClient redisson = Redisson.create(config);
List<String> list = redisson.getList("myList");
list.add("1");
list.add("2");
list.add("3");
list.remove("2");
It supports many popular codecs like Jackson JSON, Avro, Amazon Ion, Smile, CBOR, MsgPack, Kryo, FST, LZ4, Snappy and JDK Serialization
Comments
you can use the following code to store ArrayList in redis
public void saveCollection(String key, Collection<String> object) {
try {
ListOperations<String, String> listOps = redisTemplate.opsForList();
listOps.rightPushAll(key, object);
LOGGER.info("Saving collection for key {} in Redis", key);
} catch (RedisException e) {
LOGGER.error("Redis Exception", e);
}
}