为了保持所有代码的装逼性,我们先在RedisContants这个类里面添加一个常量。后面会用。
用String类型的方法
controller
@GetMapping("list")
public Result queryTypeList() {
return typeService.queryTypeList();
}
ShopTypeServiceImpl
package com.hmdp.service.impl;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
import static com.hmdp.utils.RedisConstants.SHOP_LIST_KEY;
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
@Resource
private StringRedisTemplate stringRedisTemplate;
@Override
public Result queryTypeList() {
String shopListJson = stringRedisTemplate.opsForValue().get(SHOP_LIST_KEY);
if (StrUtil.isNotBlank(shopListJson)) {
List<ShopType> shopTypeList = JSONUtil.toList(shopListJson, ShopType.class);
return Result.ok(shopTypeList);
}
List<ShopType> shopTypeList = query().orderByAsc("sort").list();
if (CollectionUtil.isEmpty(shopTypeList)) {
return Result.fail("出错了,数据不存在");
}
String jsonStr = JSONUtil.toJsonStr(shopTypeList);
stringRedisTemplate.opsForValue().set(SHOP_LIST_KEY, jsonStr);
return Result.ok(shopTypeList);
}
}
用list类型的方法
(前面都一样)。将对应部分给他提换掉就可以了。
@Resource
private StringRedisTemplate stringRedisTemplate;
@Override
public Result queryTypeList() {
List<String> shopTypeList = stringRedisTemplate.opsForList().range(SHOP_LIST_KEY, 0, -1);
if(CollectionUtil.isNotEmpty(shopTypeList)){
List<ShopType> list = JSONUtil.toList(shopTypeList.get(0), ShopType.class);
return Result.ok(list);
}
List<ShopType> typeList = query().orderByAsc("sort").list();
if(CollectionUtil.isEmpty(typeList)){
return Result.fail("列表信息不存在");
}
String jsonStr = JSONUtil.toJsonStr(typeList);
stringRedisTemplate.opsForList().leftPushAll(SHOP_LIST_KEY, jsonStr);
return Result.ok(typeList);
}