为 Shiro 自定义一个 Spring Boot HealthIndicator 检查 Redis 会话连接。

解读

国内生产环境普遍把 Shiro 的会话托管到 Redis,以实现 分布式水平扩容 与 故障转移。Spring Boot Actuator 的 /actuator/health 端点已成为 阿里、字节、美团 等公司的 必检 URL,若 Shiro 的 Redis 会话层不可用,整个网关链路会被 Nginx 或 K8s 探针 直接判定为宕机。因此,面试官希望看到你:

  1. 能 主动暴露 Shiro-Redis 的健康细节,而不是只检查 Spring-Data-Redis 的通用连接;
  2. 能在 高并发 下快速失败,不阻塞业务线程;
  3. 能 兼容集群与哨兵 两种主流 Redis 架构;
  4. 能在 健康异常 时输出 可运维的提示(如 Redis 节点 IP、Slot 缺失、密码错误等)。

知识点

  • Shiro 会话存储抽象:SessionDAO → RedisSessionDAO(或自定义实现)
  • Spring Boot Actuator 扩展点:HealthIndicator / ReactiveHealthIndicator
  • Redis 连接模型:Jedis/Lettuce 连接池、PING 命令、READONLY 状态、Cluster slots 完整性
  • 线程安全与超时控制:CompletableFuture.get(timeout)、断路器(如 Sentinel)
  • 日志规范:统一使用 health logger,避免打印敏感配置(password、节点 IP 全量)
  • 国产中间件适配:阿里云 Tair、腾讯云 CRS 对 PING 返回 PONG 以外的特殊响应码需特殊处理

答案

@Component
@ConditionalOnProperty(name = "shiro.session.store-type", havingValue = "redis")
public class ShiroRedisHealthIndicator implements HealthIndicator {

    private static final Logger healthLog = LoggerFactory.getLogger("health");

    /** 直接注入 Shiro 使用的 Redis 客户端,确保检查的是同一条连接池 */
    private final RedisTemplate<String, Session> shiroRedisTemplate;

    /** 动态配置,方便运维灰度 */
    @Value("${shiro.health.redis.timeout:500}")
    private long timeoutMillis;

    public ShiroRedisHealthIndicator(
            @Qualifier("shiroRedisTemplate") RedisTemplate<String, Session> shiroRedisTemplate) {
        this.shiroRedisTemplate = shiroRedisTemplate;
    }

    @Override
    public Health health() {
        try {
            /* 1. 异步探测,防止阻塞 actuator 线程 */
            CompletableFuture<String> future = CompletableFuture.supplyAsync(() ->
                    shiroRedisTemplate.getConnectionFactory().getConnection().ping(), 
                    ForkJoinPool.commonPool());

            String pong = future.get(timeoutMillis, TimeUnit.MILLISECONDS);

            /* 2. 国产云 Redis 可能返回 TAIR_OK 等扩展响应 */
            if (!"PONG".equalsIgnoreCase(pong) && !pong.startsWith("TAIR_OK")) {
                return Health.down()
                        .withDetail("reason", "unexpected PING response")
                        .withDetail("response", pong)
                        .build();
            }

            /* 3. 集群场景下再验证 slots 完整性 */
            if (shiroRedisTemplate.getConnectionFactory() instanceof LettuceConnectionFactory lcf
                    && lcf.isClusterAware()) {
                Iterable<RedisClusterNode> nodes = lcf.getClusterConnection().clusterGetNodes();
                long failCount = StreamSupport.stream(nodes.spliterator(), false)
                        .filter(node -> node.is(RedisClusterNode.Flag.FAIL))
                        .count();
                if (failCount > 0) {
                    return Health.down()
                            .withDetail("reason", "cluster node fail")
                            .withDetail("failCount", failCount)
                            .build();
                }
            }

            return Health.up()
                    .withDetail("mode", shiroRedisTemplate.getConnectionFactory() instanceof LettuceConnectionFactory lcf && lcf.isClusterAware() ? "cluster" : "single")
                    .build();

        } catch (TimeoutException e) {
            healthLog.warn("ShiroRedisHealthIndicator timeout after {} ms", timeoutMillis);
            return Health.down()
                    .withDetail("reason", "ping timeout")
                    .withDetail("timeoutMillis", timeoutMillis)
                    .build();
        } catch (Exception e) {
            healthLog.error("ShiroRedisHealthIndicator error", e);
            return Health.down()
                    .withDetail("reason", e.getClass().getSimpleName() + ": " + e.getMessage())
                    .build();
        }
    }
}

使用要点

  1. 必须给 RedisTemplate 打 @Qualifier("shiroRedisTemplate"),确保检查的是 Shiro 专用实例,而非 Spring Cache 那一套。
  2. 超时时间 默认 500 ms,可通过配置中心 动态推送,避免 Redis 抖动造成 大面积 POD 重启。
  3. 返回的 detail 字段只给 运维系统 消费,禁止返回密码、主节点 IP 全量列表,防止信息泄露。
  4. 若公司使用 Sentinel 模式,可再补充 ROLE SENTINEL 与 master-name 校验,思路同上。

拓展思考

  1. 双写场景一致性:如果业务同时把会话写到 Redis 与 MySQL 做冷备,健康指标需要 双通道探测,并在 DOWN 时触发 降级开关(切到 DB 会话)。
  2. 多租户隔离:ToB SaaS 平台每个租户独占 Redis DB Index,健康指标应循环探测 所有 DB Index,任一失败即 整体 DOWN,防止 A 租户会话污染 B 租户。
  3. Reactive 栈:在 Spring WebFlux + Shiro 1.10+ 的 响应式会话存储 场景,需实现 ReactiveHealthIndicator,用 Lettuce 的 ReactiveRedisConnection 做 非阻塞 PING。
  4. 混沌工程:结合 阿里 ChaosBlade,模拟 Redis 网络延迟 > 600 ms,验证健康指标能否 及时 DOWN 并触发 K8s 自动迁移,这是 P7/P8 面试 常问的 高可用闭环 题目。