3.7 KiB
3.7 KiB
title, date
| title | date |
|---|---|
| SpringBoot Redis简介和使用 | 2026-03-22 |
一、简介
Redis是一个高性能的开源内存数据库,用作缓存、数据库和消息中间件。它以极快的读写速度(基于内存存储)支持字符串、列表、哈希等多种数据结构。Redis提供数据持久化、主从复制、哨兵模式等高可用特性,广泛应用于缓存、会话存储、排行榜、消息队列等场景。
二、安装
- 通过apt包管理器安装:
sudo apt update
sudo apt install redis-server
sudo systemctl enable redis-server
- 配置远程和密码访问(可选)
打开/etc/redis/redis.conf文件,更改配置:
bind 0.0.0.0 ::1
protected-mode yes
requirepass password
systemctl restart redis-server重启服务。
三、SpringBoot使用
3.1 引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
3.2 配置文件
spring:
data:
redis:
host: 127.0.0.1
port: 6379
password: 123456
::: tip SpringBoot2中没有data层级 :::
3.3 简单使用
@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 设备在线功能
实现一个统计设备是否实时在线的功能。
@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;
}
}
客户端每30秒调用一次/device/heartbeat接口。