--- 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 org.springframework.boot spring-boot-starter-data-redis ``` ## 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 scanKeys(String pattern) { return redis.execute((RedisCallback>) connection -> { Set keys = new HashSet<>(); ScanOptions options = ScanOptions.scanOptions().match(pattern).count(1000).build(); try (Cursor 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 设备在线功能   实现一个统计设备是否实时在线的功能。 ```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 getOnlineDevices() { Set keys = redisUtils.scanKeys(HEARTBEAT_KEY + "*"); Set deviceIds = new HashSet<>(); for (String key : keys) { String deviceId = key.substring(HEARTBEAT_KEY.length()); deviceIds.add(deviceId); } return deviceIds; } } ```   客户端每30秒调用一次`/device/heartbeat`接口。