java redisTemplate存取完整的list
RedisTemplate提供了几种方法来存取完整的List。
- 使用opsForList()方法获取ListOperations对象,然后使用其leftPushAll()或rightPushAll()方法将整个List存入Redis中。
ListOperations<String, Object> listOps = redisTemplate.opsForList();
listOps.leftPushAll("mylist", myList);
- 使用opsForValue()方法获取ValueOperations对象,然后使用其set()方法将List转为JSON字符串存入Redis中。
ValueOperations<String, Object> valueOps = redisTemplate.opsForValue();
valueOps.set("mylist", new ObjectMapper().writeValueAsString(myList));
- 使用opsForHash()方法获取HashOperations对象,然后使用其putAll()方法将List转为Map存入Redis中。
HashOperations<String, Object, Object> hashOps = redisTemplate.opsForHash();
Map<Object, Object> map = new HashMap<>();
for (int i = 0; i < myList.size(); i++) {
map.put(String.valueOf(i), myList.get(i));
}
hashOps.putAll("mylist", map);
注意:以上方法中的"mylist"是Redis中的key,myList是要存入Redis的List。在读取时,需要根据存储方式选择相应的方法进行读取操作
原文地址: https://www.cveoy.top/t/topic/hNJ9 著作权归作者所有。请勿转载和采集!