feat:增加Redis文档

This commit is contained in:
2026-03-22 16:25:37 +08:00
parent a0c40be4b6
commit 681aff8bd5
2 changed files with 144 additions and 1 deletions

View File

@@ -0,0 +1,142 @@
---
title: SpringBoot Redis简介和使用
date: 2026-03-22
---
# 一、简介
  Redis是一个高性能的开源内存数据库用作缓存、数据库和消息中间件。它以极快的读写速度基于内存存储支持字符串、列表、哈希等多种数据结构。Redis提供数据持久化、主从复制、哨兵模式等高可用特性广泛应用于缓存、会话存储、排行榜、消息队列等场景。
# 二、安装
1. 通过apt包管理器安装
```bash
sudo apt update
sudo apt install redis-server
sudo systemctl enable redis-server
```
2. 配置远程和密码访问(可选)
  打开`/etc/redis/redis.conf`文件,更改配置:
```conf
bind 0.0.0.0 ::1
protected-mode yes
requirepass password
```
  `systemctl restart redis-server`重启服务。
# 三、SpringBoot使用
## 3.1 引入依赖
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
```
## 3.2 配置文件
```yml
spring:
data:
redis:
host: 127.0.0.1
port: 6379
password: 123456
```
::: tip
SpringBoot2中没有data层级
:::
## 3.3 简单使用
```java
@Component
public class RedisUtils {
@Resource
private StringRedisTemplate redis;
public void set(String key, String value, long seconds) {
redis.opsForValue().set(key, value, seconds, TimeUnit.SECONDS);
}
public String get(String key) {
return redis.opsForValue().get(key);
}
public void delete(String key) {
redis.delete(key);
}
public Boolean hasKey(String key) {
return redis.hasKey(key);
}
// 匹配查询
public Set<String> scanKeys(String pattern) {
return redis.execute((RedisCallback<Set<String>>) connection -> {
Set<String> keys = new HashSet<>();
ScanOptions options = ScanOptions.scanOptions().match(pattern).count(1000).build();
try (Cursor<byte[]> cursor = connection.keyCommands().scan(options)) {
while (cursor.hasNext()) {
keys.add(new String(cursor.next(), StandardCharsets.UTF_8));
}
} catch (Exception e) {
throw new RuntimeException("Redis SCAN 执行失败pattern=" + pattern, e);
}
return keys;
});
}
}
```
::: tip
生产环境中使用`scan`命令批量查询`key`值,`keys`命令会阻塞`Redis`线程。
:::
# 四、实战
## 4.1 设备在线功能
&emsp;&emsp;实现一个统计设备是否实时在线的功能。
```java
@RestController
@RequestMapping("/device")
public class DeviceController {
@Resource
private RedisUtils redisUtils;
private static final String HEARTBEAT_KEY = "device:heartbeat:";
private static final long EXPIRE_SECONDS = 40;
/**
* 设备心跳接口
* 设备每20-30秒调用一次
* 心跳key 40秒后过期过期即认为设备离线
*/
@PostMapping("/heartbeat")
public Boolean heartbeat(@RequestParam String deviceId) {
redisUtils.set(HEARTBEAT_KEY + deviceId, String.valueOf(System.currentTimeMillis()), EXPIRE_SECONDS);
return Boolean.TRUE;
}
/**
* 获取当前在线设备列表
*/
@GetMapping("/online")
public Set<String> getOnlineDevices() {
Set<String> keys = redisUtils.scanKeys(HEARTBEAT_KEY + "*");
Set<String> deviceIds = new HashSet<>();
for (String key : keys) {
String deviceId = key.substring(HEARTBEAT_KEY.length());
deviceIds.add(deviceId);
}
return deviceIds;
}
}
```
&emsp;&emsp;客户端每30秒调用一次`/device/heartbeat`接口。