- redis 之list使用
注入以下RedisTemplate
@Autowired
private RedisTemplate<String,String> redisTemplate;
实践demo
public List<UserLoginListDTO> getUserLoginList(BatchAddUserDTO batchAddUserDTO) {
String key = "remark_" + batchAddUserDTO.getRemark();
if (Objects.isNull(batchAddUserDTO) || Strings.isEmpty(batchAddUserDTO.getRemark())) {
return Lists.newArrayList();
}
// 先查缓存,缓存里面没有,查库并写入缓存,key为remark
String json = redisTemplate.opsForList().leftPop(key);
List<UserLoginListDTO> redisList = JSONArray.parseArray(json,UserLoginListDTO.class);
if (CollectionUtils.isNotEmpty(redisList)) {
return redisList;
}
// 查库
List<UserLoginListDTO> list = systemUserService.getUserLoginList(batchAddUserDTO);
if (CollectionUtils.isEmpty(list)) {
return Lists.newArrayList();
} else {
redisTemplate.opsForList().leftPush(key, JSON.toJSONString(list));
return list;
}
}
Demo:
List<String> list1=new ArrayList<String>();
list1.add("a1");
list1.add("a2");
list1.add("a3");
List<String> list2=new ArrayList<String>();
list2.add("b1");
list2.add("b2");
list2.add("b3");
redisTemplate.opsForList().leftPush("listkey1",list1);
redisTemplate.opsForList().rightPush("listkey2",list2);
List<String> resultList1=(List<String>)redisTemplate.opsForList().leftPop("listkey1");
List<String> resultList2=(List<String>)redisTemplate.opsForList().rightPop("listkey2");
System.out.println("resultList1:"+resultList1);
System.out.println("resultList2:"+resultList2);
运行结果:
resultList1:[a1, a2, a3]
resultList2:[b1, b2, b3]
- 保存和存取Set
SetOperations<String, String> set = redisTemplate.opsForSet();
set.add("set1","22");
set.add("set1","33");
set.add("set1","44");
Set<String> resultSet =redisTemplate.opsForSet().members("set1");
System.out.println("resultSet:"+resultSet);
运行结果为:
resultSet:[22, 33, 44]
- Hash结构,保存和存取map
Map<String,String> map=new HashMap<String,String>();
map.put("key1","value1");
map.put("key2","value2");
map.put("key3","value3");
map.put("key4","value4");
map.put("key5","value5");
redisTemplate.opsForHash().putAll("map1",map);
Map<String,String> resultMap= redisTemplate.opsForHash().entries("map1");
List<String>reslutMapList=redisTemplate.opsForHash().values("map1");
Set<String>resultMapSet=redisTemplate.opsForHash().keys("map1");
String value=(String)redisTemplate.opsForHash().get("map1","key1");
System.out.println("value:"+value);
System.out.println("resultMapSet:"+resultMapSet);
System.out.println("resultMap:"+resultMap);
System.out.println("resulreslutMapListtMap:"+reslutMapList);
运行结果为:
value:value1
resultMapSet:[key1, key2, key5, key3, key4]
resultMap:{key3=value3, key2=value2, key1=value1, key5=value5, key4=value4}
resulreslutMapListtMap:[value1, value2, value5, value3, value4]
- 保存和读取String
redisTemplate.opsForValue().set("key1","value1");
redisTemplate.opsForValue().set("key2","value2");
String result1=redisTemplate.opsForValue().get("key1").toString();
String result2=redisTemplate.opsForValue().get("key2").toString();
原文链接:https://blog.csdn.net/lichuangcsdn/article/details/80866182