package com.hmdp.controller;
import com.hmdp.dto.Result;
import com.hmdp.service.IShopTypeService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
/**
* <p>
* 前端控制器
* </p>
*
* @author 虎哥
* @since 2021-12-22
*/
@RestController
@RequestMapping("/shop-type")
public class ShopTypeController {
@Resource
private IShopTypeService typeService;
@GetMapping("list")
public Result queryTypeList() {
return typeService.queryList();
}
}
package com.hmdp.service;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* 服务类
* </p>
*
* @author 虎哥
* @since 2021-12-22
*/
public interface IShopTypeService extends IService<ShopType> {
Result queryList();
}
package com.hmdp.service.impl;
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.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.sql.Struct;
import java.util.List;
import static com.hmdp.utils.RedisConstants.SHOP_TYPE_KEY;
/**
* <p>
* 服务实现类
* </p>
*
* @author 虎哥
* @since 2021-12-22
*/
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Override
public Result queryList() {
//1.从redis获取缓存
String shopCache = stringRedisTemplate.opsForValue().get(SHOP_TYPE_KEY);
//判断是否命中
if (StrUtil.isNotBlank(shopCache)) {
//将json转成List对象返回
List<ShopType> shopType = JSONUtil.toList(shopCache, ShopType.class);
return Result.ok(shopType);
}
//未命中,查询数据库中的信息
List<ShopType> list = query().orderByAsc("sort").list();
if (list ==null) {
return Result.fail("数据库中不存在该分类");
}
//写入redis,把List对象转为json
stringRedisTemplate.opsForValue().set(SHOP_TYPE_KEY,JSONUtil.toJsonStr(list));
return Result.ok(list);
}
}