*Spring Boot 整合 Redis 教程:Lettuce、缓存与连接池配置

Spring Boot 整合 Redis 通常使用 spring-boot-starter-data-redis,默认客户端为 Lettuce。本文以 Spring Boot 3.x 和 Java 17 及以上环境为例,完成 Maven 依赖、连接配置、StringRedisTemplate 读写、声明式缓存、连接池和生产环境检查。

*1. 准备 Redis 与 Spring Boot 项目

先启动 Redis,并用命令行确认连接:

redis-cli -h 127.0.0.1 -p 6379 PING
# PONG

生产环境不要直接开放无认证的公网端口。密码、ACL、网络隔离和 TLS 应按目标部署环境配置,详见 Redis 安全文档。

*2. 添加 Maven 依赖

在 pom.xml 中加入 Spring Data Redis starter:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

版本由项目的 Spring Boot 父工程或依赖管理统一控制,不建议随意混用不同代际的 Spring Boot 与 Spring Data Redis。

如果需要配置 Lettuce 连接池,再添加:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
</dependency>

不使用连接池配置时,不必为了示例强行增加该依赖。连接池大小应根据应用实例数、并发量和 Redis 最大连接数规划。

*3. 配置 Redis 连接

application.yml 示例:

spring:
  data:
    redis:
      host: 127.0.0.1
      port: 6379
      timeout: 2s
      lettuce:
        pool:
          enabled: true
          max-active: 16
          max-idle: 8
          min-idle: 2
          max-wait: 500ms

启用认证时可以增加:

spring:
  data:
    redis:
      username: default
      password: ${REDIS_PASSWORD}

密码通过环境变量或密钥管理系统注入,不要提交到仓库。username 是否需要取决于 Redis ACL 配置。

timeout 和连接池参数只是示例。超时过短会放大正常抖动,过长会占用应用线程;连接池过大则可能耗尽 Redis 连接和服务器资源。

*4. 使用 StringRedisTemplate 读写

StringRedisTemplate 适合字符串值、计数器和简单缓存:

package com.example.demo;

import java.time.Duration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

## 

public class ProductCacheService {

    private final StringRedisTemplate redisTemplate;

    public ProductCacheService(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public void cacheProductName(long productId, String name) {
        String key = "cache:product:" + productId + ":name";
        redisTemplate.opsForValue().set(key, name, Duration.ofMinutes(10));
    }

    public String findProductName(long productId) {
        String key = "cache:product:" + productId + ":name";
        return redisTemplate.opsForValue().get(key);
    }

    public void evictProductName(long productId) {
        String key = "cache:product:" + productId + ":name";
        redisTemplate.delete(key);
    }
}

缓存键应包含明确的业务前缀和数据标识,并设置 TTL。不要用随机参数无节制拼接键,也不要在请求链路中执行 KEYS *。

StringRedisTemplate 返回 null 通常表示缓存未命中,不等于数据库中不存在数据。只有查询数据库并明确得到空结果后,才能按缓存穿透策略缓存短期空标记。

*5. 使用 RedisTemplate 保存对象

RedisTemplate<Object, Object> 或 RedisTemplate<String, Object> 可以配置键和值的序列化器。对象缓存需要明确:

  • 使用 JSON、JDK 还是其他序列化方式。
  • 类结构变化后如何兼容旧缓存。
  • 是否保存类型信息,以及如何限制可反序列化类型。
  • 序列化失败时是否允许回源和清除坏缓存。

不要为了省事在生产环境无约束地启用多态类型反序列化。字段变化频繁的聚合对象,也可以保存为 Hash 或按字段拆分,详见 Redis 数据类型。

*6. 使用 @Cacheable 声明式缓存

在配置类上启用缓存:

package com.example.demo;

import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Configuration;

## 

## 

public class CacheConfig {
}

服务方法示例:

package com.example.demo;

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

## 

public class ProductService {

    private final ProductRepository repository;

    public ProductService(ProductRepository repository) {
        this.repository = repository;
    }

    @Cacheable(cacheNames = "product", key = "#id")
    public Product findById(long id) {
        return repository.findById(id);
    }

    @CacheEvict(cacheNames = "product", key = "#product.id")
    public Product update(Product product) {
        return repository.update(product);
    }
}

这里的 ProductRepository 代表项目自己的数据库访问组件。真实项目还应处理数据库异常、空值策略和更新失败后的缓存补偿。

同一个类内部直接调用带 @Cacheable 的方法,通常不会经过 Spring 代理,缓存注解可能不会生效。事务边界和缓存失效顺序也需要一起检查。

*7. 设置缓存默认 TTL

可以自定义 RedisCacheManager 的默认配置:

package com.example.demo;

import java.time.Duration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;

## 

public class RedisCacheManagerConfig {

    @Bean
    RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {
        RedisCacheConfiguration configuration = RedisCacheConfiguration
                .defaultCacheConfig()
                .entryTtl(Duration.ofMinutes(10));

        return RedisCacheManager.builder(connectionFactory)
                .cacheDefaults(configuration)
                .build();
    }
}

不同业务的新鲜度要求不同,可以按 cache name 分别设置 TTL。随机 TTL、空值缓存和热点重建策略见 缓存穿透、击穿和雪崩防护。

*8. 实现基本的缓存读写流程

常见 Cache Aside 流程为:

读取:先查 Redis → 未命中查数据库 → 回填 Redis 并设置 TTL
更新:数据库事务提交成功 → 删除缓存 → 删除失败进入重试或修复流程

直接“双写 Redis 和数据库”并不能自动保证一致。强一致数据不能只靠缓存注解或分布式锁,详见 Redis 和数据库数据一致性方案。

*9. 常见问题排查

*无法连接 Redis

检查 host、port、防火墙、认证、TLS 和应用实际加载的配置文件。不要只看本机 redis-cli 成功,应确认应用容器或主机到 Redis 的网络也可达。

*连接数持续增长

检查是否绕过框架反复创建客户端、连接池是否过大、应用实例数是否超过容量规划,以及慢请求是否导致连接长期占用。

*缓存反序列化失败

核对生产者和消费者的序列化配置、类版本和类型信息。清理错误缓存前应确认数据可以重建,并记录具体键前缀和失败原因。

*更新后仍读到旧值

检查数据库事务是否已提交、缓存删除是否执行、同类内部调用是否绕过代理,以及并发读是否回填了旧值。必要时增加版本号、失败重试和 TTL。

*Redis 故障导致应用大量超时

设置合理的连接和命令超时,限制重试次数并加入退避。对可降级场景定义旧值或默认结果,避免所有请求同步等待后集中打向数据库。

*上线检查清单

  • Spring Boot、Spring Data Redis 和 Lettuce 版本由项目依赖管理统一维护。
  • Redis 地址、凭据和 TLS 配置不写入公开仓库。
  • 缓存键有业务前缀和 TTL,大对象与集合有容量限制。
  • 连接池、超时和重试经过真实并发压测。
  • 缓存更新明确数据库与 Redis 的先后次序和失败补偿。
  • 已覆盖缓存未命中、空值、反序列化失败和 Redis 不可用测试。
  • 监控连接池等待、Redis 延迟、错误率、缓存命中和数据库回源。

相关阅读:Java 使用 Redis、Redis 客户端与工具、Redis 实现秒杀系统、Redis 监控与告警。