黑马点评 - 商铺类型缓存练习题(Redis List实现)

首先明确返回值是一个 List<ShopType> 类型那么我们修改此函数并在 TypeService 中声明 queryTypeList 方法,并在其实现类中实现此方法

java 复制代码
    @GetMapping("list")
    public Result queryTypeList() {
        return typeService.queryTypeList();
    }

实现此方法首先需要明确数据类型,我选择的是 List ,可以方便的实现数据的读写,代码如下

java 复制代码
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryTypeList() {
//        1.从 redis 查询商铺列表
        String key = "cache:shoplist";
        List<ShopType> typeList = BeanUtil
                .copyToList(stringRedisTemplate.opsForList().range(key, 0, -1), ShopType.class);
//        2.命中,直接返回
        if (typeList != null && !typeList.isEmpty()) {
            return Result.ok(typeList);
        }
//        3.未命中,查询数据库
        typeList = query().orderByAsc("sort").list();
//        4.将商铺列表保存至 redis
        for (ShopType shopType : typeList) {
            stringRedisTemplate.opsForList().leftPush(key, shopType.getName());
        }
//        5.返回店铺列表
        return Result.ok(typeList);
    }
}

运行之后刷新网页可以发现店铺列表已经存储到了 Redis 中了!

相关推荐
栈溢出了35 分钟前
Redis 分片集群与哈希槽笔记
java·redis·笔记·spring
IpdataCloud39 分钟前
跨境AI金融风险怎么防?IP风险画像的实战应用指南
数据库·tcp/ip·金融·ip
Alan_752 小时前
API 接口慢调用根因定位:从 TCP 建连到数据库 IO 的全栈排查实战
数据库
Lihua奏3 小时前
Redis:它不只是缓存,还是高并发系统的工具箱
redis
多巴胺梦想家3 小时前
事务与并发控制:当多人同时操作数据库
服务器·数据库·oracle
howard20054 小时前
PostgreSQL起步
数据库·postgresql
秋田君5 小时前
QT_QT布局详解
开发语言·数据库·qt
可乐ea5 小时前
【Redis八股|第8篇】Redis 分布式锁原理与 Redisson 使用
数据库·redis·分布式·面试题·redis八股
李燚5 小时前
Eino devops 调试系统源码:GraphCompileCallback 怎么工作(第50篇-E36)
数据库·golang·agent·devops·graphql·aiagent·eino
ClouGence6 小时前
Oracle 到 OceanBase 迁移方案横评:停机导出/导入 vs OMS vs CDC 工具
数据库·oracle