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

ShopTypeServiceImpl类 代码

java 复制代码
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 {
    @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<ShopType> shopTypeList = JSONUtil.toList(shopType, ShopType.class);
            return Result.ok(shopTypeList);
        }
        //未查询到,查数据库
        List<ShopType> shopTypeList = query().orderByAsc("sort").list();
        String jsonStr = JSONUtil.toJsonStr(shopTypeList);
        //写入redis
        redisTemplate.opsForValue().set(key,jsonStr);
        //返回数据
        return Result.ok(shopTypeList);
    }
}
相关推荐
huazhixuthink1 小时前
PostgreSQL三种关闭方式的区别
数据库·postgresql
失散131 小时前
并发编程——17 CPU缓存架构详解&高性能内存队列Disruptor实战
java·缓存·架构·并发编程
B1118521Y465 小时前
flask的使用
后端·python·flask
only-qi5 小时前
146. LRU 缓存
java·算法·缓存
阿里小阿希5 小时前
Vue3 + Element Plus 项目中日期时间处理的最佳实践与数据库设计规范
数据库·设计规范
xuxie136 小时前
SpringBoot文件下载(多文件以zip形式,单文件格式不变)
java·spring boot·后端
白鹭6 小时前
MySQL源码部署(rhel7)
数据库·mysql
重生成为编程大王7 小时前
Java中的多态有什么用?
java·后端
666和7777 小时前
Struts2 工作总结
java·数据库
还听珊瑚海吗7 小时前
SpringMVC(一)
数据库