黑马点评商户查询缓存--缓存更新策略
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;/*** <p>* 服务实现类* </p>** @author 虎哥* @since 2021-12-22*/
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {@Autowiredprivate StringRedisTemplate redisTemplate;@Overridepublic Result queryTypeList() {String key = RedisConstants.CACHE_SHOP_KEY;//从redis中获取列表数据String shopType = redisTemplate.opsForValue().get(key);//查询到数据,直接返回if (shopType != null) {List<ShopType> shopTypeList = JSONUtil.toList(shopType, ShopType.class);return Result.ok(shopTypeList);}//未查询到,查数据库List<ShopType> shopTypeList = query().orderByAsc("sort").list();String jsonStr = JSONUtil.toJsonStr(shopTypeList);//写入redisredisTemplate.opsForValue().set(key,jsonStr);//返回数据return Result.ok(shopTypeList);}
}