黑马点评商户查询缓存--缓存更新策略

ShopTypeServiceImpl类 代码

package com.hmdp.service.impl;

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 com.hmdp.utils.RedisConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 

* 服务实现类 *

* * @author 虎哥 * @since 2021-12-22 */ @Service public class ShopTypeServiceImpl extends ServiceImpl implements IShopTypeService { @Autowired private StringRedisTemplate redisTemplate; @Override public Result queryTypeList() { String key = RedisConstants.CACHE_SHOP_KEY; //从redis中获取列表数据 String shopType = redisTemplate.opsForValue().get(key); //查询到数据,直接返回 if (shopType != null) { List shopTypeList = JSONUtil.toList(shopType, ShopType.class); return Result.ok(shopTypeList); } //未查询到,查数据库 List shopTypeList = query().orderByAsc("sort").list(); String jsonStr = JSONUtil.toJsonStr(shopTypeList); //写入redis redisTemplate.opsForValue().set(key,jsonStr); //返回数据 return Result.ok(shopTypeList); } }

 

 

你可能感兴趣的:(项目开发,java,后端,redis,数据库)