【中间件】redis使用

一、redis介绍
redis是一种NoSQL类型的数据库,其数据存储在内存中,因此其数据查询效率很高,很快。常被用作数据缓存分布式锁 等。SpringBoot集成了Redis,可查看开发文档Redis开发文档。Redis有自己的可视化工具Redis Desktop Manager

Redis使用RedisTemplateStringRedisTemplate类提供的方法操作redis数据。

redis使用场景:

1、即时性、数据一致性要求不高的

2、访问量大且更新频率不高的数据(读多,写少)

二、redis使用方法

  1. 导包
bash 复制代码
<!--        redis依赖包-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
    </dependencies>

说明:具体依赖包名可在Maven仓库搜索redis即可查询到

  1. 写配置
bash 复制代码
spring:
	redis:
    	host: 192.168.195.131(redis地址)

说明:redis可配置项可以ctrl+点击redis查看所有RedisProperties

  1. 使用RedisTemplateStringRedisTemplate类提供的方法操作redis数据。
bash 复制代码
@Override
    public Map<String, List<Level2CategoryVO>> getCatalogJson() {
        // 先从缓存中查,如果有则直接返回,如果没有则查数据库,再返回
        String catalogJson = redisTemplate.opsForValue().get("catalogJson");
        // 如果缓存中没有,则查数据库,将结果存到redis,再返回
        if (StringUtil.isNullOrEmpty(catalogJson)) {
            Map<String, List<Level2CategoryVO>> catalogJsonDB = this.getCatalogJsonDB();
            redisTemplate.opsForValue().set("catalogJson", JSON.toJSONString(catalogJsonDB));
            return catalogJsonDB;
        }
        return JSON.parseObject(catalogJson, new HashMap<String, List<Level2CategoryVO>>().getClass());
    }

redis可视化结果:

说明:StringRedisTemplate类是专门在redis中操作key和value均为String类型的数据。RedisTemplate则value可为对象类型。

相关推荐
睡不醒男孩03082321 小时前
第二篇:深入探索开源数据库高可用:构建基于CLup的PostgreSQL生产级高可用与读写分离架构
数据库·postgresql·开源·clup
Micro麦可乐1 天前
Spring Boot 实战:从零设计一个短链系统(含完整代码与数据库设计)
数据库·spring boot·后端·哈希算法·雪花算法·短链系统
码农阿豪1 天前
从零到一:Spring Boot快速接入金仓数据库实战
数据库·spring boot·后端
鼎讯信通1 天前
风电光缆运维提质增效:G-4000A 光缆故障追踪仪破解风场巡检难题
运维·网络·数据库
三十..1 天前
MySQL 从入门到高可用架构实战精要
运维·数据库·mysql
cfm_29141 天前
Redis五大基本数据结构底层了解
数据结构·数据库·redis
真实的菜1 天前
Redis 从入门到精通(十二):典型业务场景实战 —— 排行榜、限流器、秒杀系统、Session 共享
数据库·redis·python
你想考研啊1 天前
mysql数据库导出导入
数据库·mysql·oracle
十年编程老舅1 天前
Linux DRM:底层逻辑与实践架构
数据库·mysql
The Sheep 20231 天前
Vue复习
linux·服务器·数据库