RedisRemote Dictionary Server是一款开源的、高性能的键值对KV内存数据库同时支持数据持久化、多种数据结构、分布式部署等特性常被用于缓存、会话存储、消息队列、限流削峰等场景。1. Redis 核心特性内存存储数据默认存储在内存中读写速度极快QPS 可达 10 万 。数据持久化支持 RDB快照和 AOF日志追加两种方式避免内存数据丢失。丰富的数据结构核心支持 String、Hash、List、Set、ZSet有序集合还扩展了 Bitmap、HyperLogLog、Geo 等。原子操作所有单个命令都是原子性的支持事务弱事务、Lua 脚本实现复杂原子逻辑。高可用支持主从复制、哨兵Sentinel、集群Cluster保证服务高可用和水平扩展。2. Redis 典型应用场景缓存热点数据缓存如商品信息、用户信息减轻数据库压力。会话存储分布式系统中存储用户会话替代 Session。计数器点赞数、阅读量、限流计数INCR/DECR 原子操作。排行榜ZSet 实现实时排名如游戏积分、商品销量。消息队列List 的 LPUSH/RPOP 实现简单队列结合 BRPOP 实现阻塞队列。3、Spring boot中体现的高级特性1. 存储 Java 对象通过GenericJackson2JsonRedisSerializer序列化可直接存储 / 读取对象// 定义实体类 Data AllArgsConstructor NoArgsConstructor public class User { private Long id; private String name; private Integer age; } // Service 层添加方法 public void setUser(String key, User user) { redisTemplate.opsForValue().set(key, user, 1, TimeUnit.HOURS); } public User getUser(String key) { return (User) redisTemplate.opsForValue().get(key); } // 测试 Test public void testObject() { User user new User(1002L, 王五, 30); redisService.setUser(user:1002, user); User result redisService.getUser(user:1002); System.out.println(result); // 输出User(id1002, name王五, age30) }2. 分布式锁基于 RedisSpring Boot 中可通过 Redis 实现分布式锁主要代码/** * 分布式锁加锁 */ public boolean lock(String lockKey, String requestId, long timeout, TimeUnit unit) { return Boolean.TRUE.equals(redisTemplate.opsForValue().setIfAbsent(lockKey, requestId, timeout, unit)); } /** * 分布式锁解锁防止误删 */ public boolean unlock(String lockKey, String requestId) { // 使用 Lua 脚本保证原子性 String script if redis.call(get, KEYS[1]) ARGV[1] then return redis.call(del, KEYS[1]) else return 0 end; Long result (Long) redisTemplate.execute( new DefaultRedisScript(script, Long.class), Collections.singletonList(lockKey), requestId ); return result ! null result 0; }Spring Boot 整合 Redis的相关实现在 Spring Boot 中使用 Redis 是企业开发的主流方式核心依赖spring-boot-starter-data-redis封装了 Lettuce默认客户端提供了极简的配置和易用的RedisTemplate/StringRedisTemplate操作 API。1、引入依赖在 Spring Boot 项目中配置 Redis 连接是使用 Redis 的基础。首先在pom.xml中添加 Redis 核心依赖和连接池依赖连接池是性能关键必须加!-- Spring Data Redis 核心依赖自动适配Spring Boot版本 -- dependency groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-data-redis/artifactId /dependency !-- 连接池依赖Lettuce默认依赖但需显式引入pool2 -- dependency groupIdorg.apache.commons/groupId artifactIdcommons-pool2/artifactId /dependency !-- 可选Redisson分布式锁/高级功能AI售后高频 -- dependency groupIdorg.redisson/groupId artifactIdredisson-spring-boot-starter/artifactId version3.23.3/version /dependency2、基础连接配置application.yml/application.propertiesSpring Boot 支持yml和properties两种配置格式推荐用yml更简洁下面以application.yml为例1. 单机 Redis 配置开发 / 测试 / 中小规模生产spring: # Redis核心配置 redis: # Redis服务地址默认127.0.0.1生产填实际IP host: 127.0.0.1 # 端口默认6379若修改过需对应调整 port: 6379 # 密码无密码则注释该行生产环境必须设置密码 password: your_redis_password # 数据库索引Redis默认16个库0-15建议按业务分库 database: 0 # 超时配置连接/读取/写入超时避免无限等待 timeout: 5000ms # Lettuce客户端配置Spring Boot 2.x默认替代Jedis lettuce: # 关闭超时时间默认100ms避免连接池关闭异常 shutdown-timeout: 100ms # 连接池配置核心解决连接泄露/性能问题 pool: # 最大活跃连接数默认8生产建议10-20 max-active: 16 # 最大空闲连接数默认8建议等于max-active max-idle: 16 # 最小空闲连接数默认0建议2-5快速响应请求 min-idle: 4 # 最大等待时间-1表示无限制生产建议5000ms避免阻塞 max-wait: 5000ms2. 集群 Redis 配置大规模生产环境一般生产环境采用 Redis Cluster 集群配置如下spring: redis: # 集群节点多个节点用逗号分隔 cluster: nodes: - 192.168.1.10:6379 - 192.168.1.11:6379 - 192.168.1.12:6379 # 最大重定向次数默认5避免集群跳转过多 max-redirects: 3 # 密码集群所有节点密码需一致 password: your_redis_password # 数据库索引集群模式下仅0库生效 database: 0 timeout: 5000ms lettuce: pool: max-active: 32 max-idle: 32 min-idle: 8 max-wait: 5000ms3. 哨兵模式配置高可用单机集群spring: redis: # 哨兵配置 sentinel: # 主节点名称与Redis哨兵配置的master-name一致 master: mymaster # 哨兵节点多个用逗号分隔 nodes: 192.168.1.20:26379,192.168.1.21:26379 password: your_redis_password database: 0 timeout: 5000ms lettuce: pool: max-active: 16 max-idle: 16 min-idle: 4 max-wait: 5000ms3、序列化配置解决 Redis Key/Value 乱码Spring Boot 默认用 JDK 序列化会导致 Redis 中 Key 显示为\xAC\xED\x00\x05t\x00\x10 :token这种乱码必须自定义序列化配置核心配置代码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; /** * Redis序列化配置解决乱码问题 */ Configuration public class RedisConfig { /** * 自定义RedisTemplate通用型支持Object类型Value */ Bean public RedisTemplateString, Object redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplateString, Object redisTemplate new RedisTemplate(); // 设置连接工厂 redisTemplate.setConnectionFactory(redisConnectionFactory); // Key序列化必须为String避免乱码 StringRedisSerializer stringRedisSerializer new StringRedisSerializer(); redisTemplate.setKeySerializer(stringRedisSerializer); redisTemplate.setHashKeySerializer(stringRedisSerializer); // Value序列化JSON格式兼容对象/基本类型 GenericJackson2JsonRedisSerializer jsonSerializer new GenericJackson2JsonRedisSerializer(); redisTemplate.setValueSerializer(jsonSerializer); redisTemplate.setHashValueSerializer(jsonSerializer); // 初始化配置 redisTemplate.afterPropertiesSet(); return redisTemplate; } /** * 字符串专用RedisTemplate轻量无需序列化AI售后高频用 */ Bean public RedisTemplateString, String stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplateString, String stringRedisTemplate new RedisTemplate(); stringRedisTemplate.setConnectionFactory(redisConnectionFactory); StringRedisSerializer stringRedisSerializer new StringRedisSerializer(); stringRedisTemplate.setKeySerializer(stringRedisSerializer); stringRedisTemplate.setValueSerializer(stringRedisSerializer); stringRedisTemplate.setHashKeySerializer(stringRedisSerializer); stringRedisTemplate.setHashValueSerializer(stringRedisSerializer); stringRedisTemplate.afterPropertiesSet(); return stringRedisTemplate; } }总结核心配置Spring Boot 中 Redis 配置分基础连接host/port/password、连接池lettuce.pool、序列化解决乱码 三部分缺一不可Redis连接如何选择单机配置用于开发 / 中小规模集群 / 哨兵用于大规模生产核心场景String 用于缓存 / 计数、Hash 用于存储对象、ZSet 用于排行榜、List 用于消息队列结合过期时间和分布式锁可满足大部分业务需求。
Redis的核心知识
RedisRemote Dictionary Server是一款开源的、高性能的键值对KV内存数据库同时支持数据持久化、多种数据结构、分布式部署等特性常被用于缓存、会话存储、消息队列、限流削峰等场景。1. Redis 核心特性内存存储数据默认存储在内存中读写速度极快QPS 可达 10 万 。数据持久化支持 RDB快照和 AOF日志追加两种方式避免内存数据丢失。丰富的数据结构核心支持 String、Hash、List、Set、ZSet有序集合还扩展了 Bitmap、HyperLogLog、Geo 等。原子操作所有单个命令都是原子性的支持事务弱事务、Lua 脚本实现复杂原子逻辑。高可用支持主从复制、哨兵Sentinel、集群Cluster保证服务高可用和水平扩展。2. Redis 典型应用场景缓存热点数据缓存如商品信息、用户信息减轻数据库压力。会话存储分布式系统中存储用户会话替代 Session。计数器点赞数、阅读量、限流计数INCR/DECR 原子操作。排行榜ZSet 实现实时排名如游戏积分、商品销量。消息队列List 的 LPUSH/RPOP 实现简单队列结合 BRPOP 实现阻塞队列。3、Spring boot中体现的高级特性1. 存储 Java 对象通过GenericJackson2JsonRedisSerializer序列化可直接存储 / 读取对象// 定义实体类 Data AllArgsConstructor NoArgsConstructor public class User { private Long id; private String name; private Integer age; } // Service 层添加方法 public void setUser(String key, User user) { redisTemplate.opsForValue().set(key, user, 1, TimeUnit.HOURS); } public User getUser(String key) { return (User) redisTemplate.opsForValue().get(key); } // 测试 Test public void testObject() { User user new User(1002L, 王五, 30); redisService.setUser(user:1002, user); User result redisService.getUser(user:1002); System.out.println(result); // 输出User(id1002, name王五, age30) }2. 分布式锁基于 RedisSpring Boot 中可通过 Redis 实现分布式锁主要代码/** * 分布式锁加锁 */ public boolean lock(String lockKey, String requestId, long timeout, TimeUnit unit) { return Boolean.TRUE.equals(redisTemplate.opsForValue().setIfAbsent(lockKey, requestId, timeout, unit)); } /** * 分布式锁解锁防止误删 */ public boolean unlock(String lockKey, String requestId) { // 使用 Lua 脚本保证原子性 String script if redis.call(get, KEYS[1]) ARGV[1] then return redis.call(del, KEYS[1]) else return 0 end; Long result (Long) redisTemplate.execute( new DefaultRedisScript(script, Long.class), Collections.singletonList(lockKey), requestId ); return result ! null result 0; }Spring Boot 整合 Redis的相关实现在 Spring Boot 中使用 Redis 是企业开发的主流方式核心依赖spring-boot-starter-data-redis封装了 Lettuce默认客户端提供了极简的配置和易用的RedisTemplate/StringRedisTemplate操作 API。1、引入依赖在 Spring Boot 项目中配置 Redis 连接是使用 Redis 的基础。首先在pom.xml中添加 Redis 核心依赖和连接池依赖连接池是性能关键必须加!-- Spring Data Redis 核心依赖自动适配Spring Boot版本 -- dependency groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-data-redis/artifactId /dependency !-- 连接池依赖Lettuce默认依赖但需显式引入pool2 -- dependency groupIdorg.apache.commons/groupId artifactIdcommons-pool2/artifactId /dependency !-- 可选Redisson分布式锁/高级功能AI售后高频 -- dependency groupIdorg.redisson/groupId artifactIdredisson-spring-boot-starter/artifactId version3.23.3/version /dependency2、基础连接配置application.yml/application.propertiesSpring Boot 支持yml和properties两种配置格式推荐用yml更简洁下面以application.yml为例1. 单机 Redis 配置开发 / 测试 / 中小规模生产spring: # Redis核心配置 redis: # Redis服务地址默认127.0.0.1生产填实际IP host: 127.0.0.1 # 端口默认6379若修改过需对应调整 port: 6379 # 密码无密码则注释该行生产环境必须设置密码 password: your_redis_password # 数据库索引Redis默认16个库0-15建议按业务分库 database: 0 # 超时配置连接/读取/写入超时避免无限等待 timeout: 5000ms # Lettuce客户端配置Spring Boot 2.x默认替代Jedis lettuce: # 关闭超时时间默认100ms避免连接池关闭异常 shutdown-timeout: 100ms # 连接池配置核心解决连接泄露/性能问题 pool: # 最大活跃连接数默认8生产建议10-20 max-active: 16 # 最大空闲连接数默认8建议等于max-active max-idle: 16 # 最小空闲连接数默认0建议2-5快速响应请求 min-idle: 4 # 最大等待时间-1表示无限制生产建议5000ms避免阻塞 max-wait: 5000ms2. 集群 Redis 配置大规模生产环境一般生产环境采用 Redis Cluster 集群配置如下spring: redis: # 集群节点多个节点用逗号分隔 cluster: nodes: - 192.168.1.10:6379 - 192.168.1.11:6379 - 192.168.1.12:6379 # 最大重定向次数默认5避免集群跳转过多 max-redirects: 3 # 密码集群所有节点密码需一致 password: your_redis_password # 数据库索引集群模式下仅0库生效 database: 0 timeout: 5000ms lettuce: pool: max-active: 32 max-idle: 32 min-idle: 8 max-wait: 5000ms3. 哨兵模式配置高可用单机集群spring: redis: # 哨兵配置 sentinel: # 主节点名称与Redis哨兵配置的master-name一致 master: mymaster # 哨兵节点多个用逗号分隔 nodes: 192.168.1.20:26379,192.168.1.21:26379 password: your_redis_password database: 0 timeout: 5000ms lettuce: pool: max-active: 16 max-idle: 16 min-idle: 4 max-wait: 5000ms3、序列化配置解决 Redis Key/Value 乱码Spring Boot 默认用 JDK 序列化会导致 Redis 中 Key 显示为\xAC\xED\x00\x05t\x00\x10 :token这种乱码必须自定义序列化配置核心配置代码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; /** * Redis序列化配置解决乱码问题 */ Configuration public class RedisConfig { /** * 自定义RedisTemplate通用型支持Object类型Value */ Bean public RedisTemplateString, Object redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplateString, Object redisTemplate new RedisTemplate(); // 设置连接工厂 redisTemplate.setConnectionFactory(redisConnectionFactory); // Key序列化必须为String避免乱码 StringRedisSerializer stringRedisSerializer new StringRedisSerializer(); redisTemplate.setKeySerializer(stringRedisSerializer); redisTemplate.setHashKeySerializer(stringRedisSerializer); // Value序列化JSON格式兼容对象/基本类型 GenericJackson2JsonRedisSerializer jsonSerializer new GenericJackson2JsonRedisSerializer(); redisTemplate.setValueSerializer(jsonSerializer); redisTemplate.setHashValueSerializer(jsonSerializer); // 初始化配置 redisTemplate.afterPropertiesSet(); return redisTemplate; } /** * 字符串专用RedisTemplate轻量无需序列化AI售后高频用 */ Bean public RedisTemplateString, String stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplateString, String stringRedisTemplate new RedisTemplate(); stringRedisTemplate.setConnectionFactory(redisConnectionFactory); StringRedisSerializer stringRedisSerializer new StringRedisSerializer(); stringRedisTemplate.setKeySerializer(stringRedisSerializer); stringRedisTemplate.setValueSerializer(stringRedisSerializer); stringRedisTemplate.setHashKeySerializer(stringRedisSerializer); stringRedisTemplate.setHashValueSerializer(stringRedisSerializer); stringRedisTemplate.afterPropertiesSet(); return stringRedisTemplate; } }总结核心配置Spring Boot 中 Redis 配置分基础连接host/port/password、连接池lettuce.pool、序列化解决乱码 三部分缺一不可Redis连接如何选择单机配置用于开发 / 中小规模集群 / 哨兵用于大规模生产核心场景String 用于缓存 / 计数、Hash 用于存储对象、ZSet 用于排行榜、List 用于消息队列结合过期时间和分布式锁可满足大部分业务需求。