实现思路:
经查看ShopType是一个存放和商品类型相关的类,类有多个属性,目标是需要获取全部种类的相关信息。
数据结构设计:
利用redis列表lis存储,key是ShopType,value是ShopType类对应的json字符串
代码设计:
package com.hmdp.service.impl;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
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.RedisTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* <p>
* 服务实现类
* </p>
*
* @author 虎哥
* @since 2021-12-22
*/
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
@Resource
private RedisTemplate redisTemplate;
@Override
public Result queryTypeList() {
// 1. 从redis查询商铺类型:获取列表的长度
Long size = redisTemplate.opsForList().size("ShopType");
// 2. 判断是否存在
if (size!=0){
// 3. 存在,直接返回
//从redis中获取全部商铺信息
List<String> shopTypesStr=redisTemplate.opsForList().range("ShopType",0,size-1);
System.out.println("shopTypes = " + shopTypesStr);
// 创建 ObjectMapper 实例用于 JSON 转换
ObjectMapper objectMapper = new ObjectMapper();
List<ShopType> shopTypes=new ArrayList<>();
for (String jsonStr : shopTypesStr) {
try {
// 将 JSON 字符串转换为 ShopType 对象
ShopType shopType = objectMapper.readValue(jsonStr, ShopType.class);
shopTypes.add(shopType);
} catch (IOException e) {
// 处理 JSON 转换异常
System.err.println("Failed to convert JSON to ShopType: " + jsonStr);
e.printStackTrace();
}
}
return Result.ok(shopTypes);
}
// 4. 不存在,根据id查询数据库
List<ShopType> typeList=query().orderByAsc("sort").list();
// 5. 数据库不存在信息,返回404
if (typeList.size()==0){
return Result.fail("不存在仍和店铺类型");
}
// 6. 数据库存在该商铺信息,将信息写入redis
List<String> ToRedis=new ArrayList<>();
for(ShopType st:typeList){
String TR=JSONUtil.toJsonStr(st);
ToRedis.add(TR);
}
redisTemplate.opsForList().rightPushAll("ShopType", ToRedis);
// 7. 将信息返回给用户
return Result.ok(typeList);
}
}