废话不多说,直接上代码!!!
String类型
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
@Autowired
private StringRedisTemplate redisTemplate;
@Override
public Result orderList() {
// TODO String类型
String shopType = redisTemplate.opsForValue().get(CACHE_SHOP_TYPE_KEY);
if(StrUtil.isNotBlank(shopType)){
List<ShopType> shopTypeList = JSONUtil.toList(shopType, ShopType.class);
return Result.ok(shopTypeList);
}
List<ShopType> shopTypeList = query().orderByAsc("sort").list();
if(shopTypeList.isEmpty()){
return Result.fail("类型为空");
}
redisTemplate.opsForValue().set(CACHE_SHOP_TYPE_KEY,JSONUtil.toJsonStr(shopTypeList));
return Result.ok(shopTypeList);
}
}
Hash类型
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
@Autowired
private StringRedisTemplate redisTemplate;
@Override
public Result orderList() {
//TODO Hash类型
Map<Object, Object> map = redisTemplate.opsForHash().entries(CACHE_SHOP_TYPE_KEY);
if (!map.isEmpty()) {
ArrayList<Object> shopTypeList = new ArrayList<Object>((Collection<?>) map);
Result.ok(shopTypeList);
}
List<ShopType> shopTypeList = query().orderByAsc("sort").list();
if(shopTypeList.isEmpty()){
return Result.fail("类型为空");
}
Map<String, Object> shopTypeMap =null;
for (ShopType shopType : shopTypeList) {
shopTypeMap = BeanUtil.beanToMap(shopType,new HashMap<>(),
CopyOptions.create().ignoreNullValue().setFieldValueEditor((fieldName,fieldValue)->{
if (fieldValue == null){
fieldValue = "";
}else {
fieldValue = fieldValue.toString();
}
return fieldValue;
}));
redisTemplate.opsForHash().putAll(CACHE_SHOP_TYPE_KEY+shopType.getId(),shopTypeMap);
}
return Result.ok(shopTypeList);
}
}
这两种方式都是可以运行的,但是要注意的是Controller中的return语句 必须要这么写,否则就会出现图片数据都消失的情况
return typeService.orderList();