一、Redis 简介
Redis(Remote Dictionary Server)是一个开源的高性能键值对存储数据库,基于内存运行并支持持久化,常用于缓存、会话存储、消息队列等场景。其核心特点包括:
- 速度快:基于内存操作,单线程模型避免上下文切换开销,读写性能极高(秒级处理 10 万 + 请求)。
- 支持多种数据类型:不仅是简单的键值对,还提供复杂结构的存储。
- 持久化:可通过 RDB(快照)和 AOF(日志)将数据持久化到磁盘,避免内存数据丢失。
- 高可用:支持主从复制、哨兵模式、集群(Cluster),保证服务稳定性。
二、Redis 主要数据类型及用法
Redis 的键(key)均为字符串类型,值(value)支持以下 5 种核心数据类型:
数据类型 | 说明 | 常用命令 | 典型场景 |
---|---|---|---|
String(字符串) | 最基本类型,可存储文本、数字(如计数器) | set、get、incr(自增)、decr(自减) | 缓存用户信息、计数器、验证码 |
Hash(哈希) | 类似 Java 的 Map,适合存储对象(字段 - 值映射) | hset、hget、hgetAll、hdel | 存储用户信息(如 id:1 {name: "张三", age: 20}) |
List(列表) | 有序列表(可重复),底层是双向链表 | lpush(左加)、rpop(右删)、lrange(范围查询) | 消息队列、最新消息列表 |
Set(集合) | 无序集合(不可重复),支持交集、并集等操作 | sadd、smembers、sinter(交集)、sunion(并集) | 标签、好友关系(共同好友) |
Sorted Set(有序集合) | 类似 Set,但每个元素关联一个分数(score),按分数排序 | zadd、zrange(按分数升序)、zrevrange(降序) | 排行榜(如销量、积分排名) |
三、SpringBoot 整合 Redis
1. 环境准备
- JDK 1.8+
- SpringBoot 2.7.x(或 3.x)
- Redis 服务(本地或远程,默认端口 6379)
2. 代码实现
新建一个名为SpringBootRedisDemo的Maven项目
(1)添加依赖
在 pom.xml
中添加 Redis 启动器:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><!-- SpringBoot父依赖 --><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.7.4</version><relativePath/></parent><groupId>com.yqd</groupId><artifactId>SpringBootRedisDemo</artifactId><version>1.0-SNAPSHOT</version><packaging>jar</packaging><name>SpringBootRedisDemo</name><url>http://maven.apache.org</url><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><dependencies><!-- SpringBoot 核心依赖 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- Redis 依赖 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><!-- 连接池(可选,推荐) --><dependency><groupId>org.apache.commons</groupId><artifactId>commons-pool2</artifactId></dependency><!-- Lombok(简化实体类) --><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build>
</project>
(2)配置 Redis 连接
在 application.yml
中配置 Redis 连接信息:
spring:redis:host: localhost # Redis 服务地址port: 6379 # 端口(默认6379)password: # 密码(若未设置则为空)database: 0 # 数据库索引(默认0)lettuce: # 使用 Lettuce 客户端(默认)pool:max-active: 8 # 最大连接数max-idle: 8 # 最大空闲连接min-idle: 2 # 最小空闲连接max-wait: 100ms # 连接等待时间
(3)编写 Redis 配置类
默认序列化会导致 Redis 中存储的 key/value 带有类名前缀,可自定义序列化器(如使用 JSON):
package com.yqd.config;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;@Configuration
public class RedisConfig {@Beanpublic RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {RedisTemplate<String, Object> template = new RedisTemplate<>();template.setConnectionFactory(factory);// 序列化配置:key 用字符串,value 用 JSONtemplate.setKeySerializer(new StringRedisSerializer());template.setValueSerializer(new GenericJackson2JsonRedisSerializer());// Hash 类型的 key/value 序列化template.setHashKeySerializer(new StringRedisSerializer());template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());template.afterPropertiesSet();return template;}
}
(4)编写实体类
package com.yqd.entity;import lombok.Data;import java.io.Serializable;@Data
public class User implements Serializable {private Long id;private String name;private Integer age;
}
(5)编写 Service 层
package com.yqd.service;import com.yqd.entity.User;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;@Service
public class RedisService {@Resourceprivate RedisTemplate<String, Object> redisTemplate;// 操作 String 类型public void setString(String key, String value, long timeout) {redisTemplate.opsForValue().set(key, value, timeout, TimeUnit.SECONDS);}public String getString(String key) {return (String) redisTemplate.opsForValue().get(key);}// 操作 Hash 类型(存储 User 对象)public void setHash(String key, String hashKey, User user) {redisTemplate.opsForHash().put(key, hashKey, user);}public User getHash(String key, String hashKey) {return (User) redisTemplate.opsForHash().get(key, hashKey);}// 操作 List 类型public void addList(String key, Object value) {redisTemplate.opsForList().leftPush(key, value); // 从左侧添加}public Object getList(String key, long index) {return redisTemplate.opsForList().index(key, index); // 获取指定索引元素}
}
(6)编写 Controller 层
package com.yqd.controller;import com.yqd.entity.User;
import com.yqd.service.RedisService;
import org.springframework.web.bind.annotation.*;import javax.annotation.Resource;@RestController
@RequestMapping("/redis")
public class RedisController {@Resourceprivate RedisService redisService;// 测试 String 类型@GetMapping("/string")public String testString(@RequestParam String key, @RequestParam String value) {redisService.setString(key, value, 60); // 过期时间 60 秒return "存入成功,值为:" + redisService.getString(key);}// 测试 Hash 类型@PostMapping("/hash")public User testHash(@RequestParam String key, @RequestParam String hashKey,@RequestBody User user) {redisService.setHash(key, hashKey, user);return redisService.getHash(key, hashKey);}// 测试 List 类型@GetMapping("/list")public Object testList(@RequestParam String key, @RequestParam String value) {redisService.addList(key, value);return redisService.getList(key, 0); // 获取第一个元素}
}
(7)启动类
package com.yqd;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class SpringBootRedisDemo {public static void main(String[] args) {SpringApplication.run(SpringBootRedisDemo.class, args);}
}
3. 接口测试
接口类型 | 接口地址 | 参数示例 | 预期结果 |
---|---|---|---|
POST | /api/redis/string | key=name&value=yqd&timeout=300 | 返回 “String 存储成功,获取值:yqd” |
POST | /api/redis/hash | key=users&hashKey=1001 + 请求体: | 返回存储的 User 对象 |
GET | /api/redis/list | key=messages&value=hello | 返回列表:["hello"] |
GET | /api/redis/set | key=tags&values=java,redis,java | 返回去重集合:["java","redis"] |
GET | /api/redis/zset | key=rank&value = 张三 & score=95 | 返回降序排名:["张三"] |
4. 验证 Redis 数据
通过 Redis 客户端(如redis-cli
)查看存储的数据:
# 连接Redis
redis-cli# 查看所有key
keys *# 查看String类型值
get name# 查看Hash类型值
hget users 1001