package com.hmdp.controller;
import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TYPE_KEY;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.service.IShopTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.util.List;
import javax.annotation.Resource;
/**
* <p>
* 前端控制器
* </p>
*
* @author 虎哥
* @since 2021-12-22
*/
@RestController
@RequestMapping("/shop-type")
public class ShopTypeController {
@Resource
private IShopTypeService typeService;
// 注入ObjectMapper,用于JSON的序列化和反序列化
@Autowired
private ObjectMapper objectMapper;
@Resource
private StringRedisTemplate stringRedisTemplate;
@GetMapping("list")
public Result queryTypeList() {
// 从Redis中获取缓存的商户类型列表字符串
String cacheShopListString = stringRedisTemplate.opsForValue().get(CACHE_SHOP_TYPE_KEY);
List<ShopType> shopTypeList = null;
if (cacheShopListString != null) {
try {
// 使用ObjectMapper反序列化字符串为ShopType列表
shopTypeList = objectMapper.readValue(cacheShopListString, new TypeReference<List<ShopType>>() {});
} catch (IOException e) {
// 处理反序列化异常,例如记录日志或抛出运行时异常
e.printStackTrace();
// 这里可以添加逻辑来从数据库重新加载数据并更新缓存
}
}
if (shopTypeList == null) {
// 如果缓存中没有数据或反序列化失败,则从数据库查询
shopTypeList = typeService.query().orderByAsc("sort").list();
// 将查询结果序列化为字符串并存入Redis
try {
String jsonString = objectMapper.writeValueAsString(shopTypeList);
stringRedisTemplate.opsForValue().set(CACHE_SHOP_TYPE_KEY, jsonString);
} catch (IOException e) {
// 处理序列化异常
e.printStackTrace();
}
}
return Result.ok(shopTypeList);
}
}
Redis中存储的key-value序列化为List对象
于 2024-06-27 19:56:13 首次发布