Redis中存储的key-value序列化为List对象

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);
    }
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值