缓存使用

缓存的访问流程

redis中查询缓存数据
若不存在则进行数据库查询并将缓存数据存入redis中
若存在在直接进行放回

引入缓存

首先导入spring-data-redis的pom包

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

在application.yml添加redis配置
image

RedisTemplate和StringRedisTemplate封装了对redis的操作
image

具体缓存和之前业务流程一样
若数据存在则使用jackson反序列化并返回
若不存在则查询数据库 则使用jackson 进行序列化并进行返回

    public Map<String, List<Catalog2VO>> getCatalogJson() throws JsonProcessingException {
        // 从redis进行进行获取数据
        String categoryMapStrings = redisTemplate.opsForValue().get(REDIS_CACHE_CATEGORY);
        // 判断数据是否存在
        if (StringUtils.isEmpty(categoryMapStrings)) {
            Map<String, List<Catalog2VO>> catalogJsonResult = getCatalogJsonResult();
            // 进行数据序列化
            categoryMapStrings = objectMapper.writeValueAsString(catalogJsonResult);
            redisTemplate.opsForValue().set(REDIS_CACHE_CATEGORY, categoryMapStrings);
        }

        // 进行数据反序列化 参数2可以对复杂类型进行反序列化
        return objectMapper.readValue(categoryMapStrings, new TypeReference<Map<String, List<Catalog2VO>>>() {
        });
    }
posted @   RainbowMagic  阅读(25)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示