一 、存取为list类型

  1. @RestController

  2. @RequestMapping("/test")

  3. @Slf4j

  4. public class TestController 

  5. @Autowired

  6. private RedisTemplate redisTemplate;

  7. @ApiOperation("redis-savelist")

  8. @PostMapping("/redis/save/list")

  9. public void redisSaveList() {

  10. List<Person> list = getPersonList();

  11. //清空

  12. while (redisTemplate.opsForList().size("oowwoo") > 0){

  13. redisTemplate.opsForList().leftPop("oowwoo");

  14. }

  15. //存储

  16. redisTemplate.opsForList().rightPushAll("oowwoo", list);

  17. //取出

  18. List<Person> oowwoo = redisTemplate.opsForList().range("oowwoo", 0, -1);

  19. log.info(">>>>>>>>>>>>>>>list = {}", oowwoo.toString());

  20. Iterator<Person> it = oowwoo.iterator();

  21. while(it.hasNext()){

  22. Person p = it.next();

  23. log.info("person = {}", p.toString());

  24. }

  25. }

  26. private List<Person> getPersonList() {

  27. Person p1 = new Person();

  28. p1.setId(1L);

  29. p1.setName("张一");

  30. p1.setAge(11);

  31. Person p2 = new Person();

  32. p2.setId(2L);

  33. p2.setName("张二");

  34. p2.setAge(22);

  35. Person p3 = new Person();

  36. p3.setId(3L);

  37. p3.setName("张三");

  38. p3.setAge(33);

  39. List<Person> list = new ArrayList<>();

  40. list.add(p1);

  41. list.add(p2);

  42. list.add(p3);

  43. return list;

  44. }

  45. }

二 、将list转为json对象存取

  1. import com.alibaba.fastjson.JSON;

  2. import com.alibaba.fastjson.JSONObject;

  3. @Autowired

  4. private StringRedisTemplate stringRedisTemplate;

  5. //存

  6. List<Long> businessIdList = eeFreecarriageShopService.selectBusinessIdInPromotion();

  7. stringRedisTemplate.opsForValue().set(RedisConstants.FREECARRIAGE_BUSINESSIDLIST, JSON.toJSON(businessIdList).toString());

  8. //取

  9. String businessJsonArray = stringRedisTemplate.opsForValue().get(RedisConstants.FREECARRIAGE_BUSINESSIDLIST);

  10. List<Long> businessIdList = JSONObject.parseArray(businessJsonArray, Long.class);

 
java 用redisTemplate 的 Operations存取list集合

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐