You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Lettuce Redis客户端未在订阅者中获取Command Latency Event问题

解决Lettuce Redis命令延迟事件未采集问题

核心问题定位

配置Lettuce命令延迟监控后仅捕获到连接事件,未采集到命令执行延迟事件,本质是延迟监控配置未正确绑定到Redis客户端实例,或命令执行流程未触发延迟事件逻辑。

具体修复步骤

1. 正确配置ClientResources与延迟监听器

Lettuce的命令延迟事件依赖ClientResources中的发布/订阅机制,需显式注册监听器并关联到客户端:

@Bean
public ClientResources clientResources() {
    DefaultClientResources resources = DefaultClientResources.builder()
            .commandLatencyRecorder(new DefaultCommandLatencyRecorder())
            .commandLatencyPublisherOptions(CommandLatencyPublisherOptions.defaultOptions())
            .build();
    
    // 注册自定义延迟监听器
    resources.commandLatencyPublisher().subscribe(latencies -> {
        for (CommandLatency latency : latencies) {
            // 处理延迟日志,比如打印命令、耗时等
            System.out.printf("Command: %s, Latency: %dns%n", 
                latency.getCommandType(), latency.getDuration().toNanos());
        }
    });
    return resources;
}

2. 将ClientResources绑定到Redis连接工厂

确保Spring的RedisConnectionFactory使用上述配置的ClientResources,避免默认无监控的客户端实例:

@Bean
public RedisConnectionFactory redisConnectionFactory(ClientResources clientResources) {
    RedisStandaloneConfiguration redisConfig = new RedisStandaloneConfiguration("localhost", 6379);
    LettuceClientConfiguration clientConfig = LettuceClientConfiguration.builder().build();
    
    LettuceConnectionFactory factory = new LettuceConnectionFactory(redisConfig, clientConfig);
    factory.setClientResources(clientResources);
    return factory;
}

3. 验证命令执行的客户端实例

执行Redis命令时,必须使用Spring注入的RedisTemplate或StringRedisTemplate,它们会自动复用配置好的连接工厂实例,避免手动创建未配置监控的Lettuce客户端。

4. 检查延迟事件触发条件

  • 命令延迟事件仅在**命令执行完成(成功/失败)**后触发,确保代码中确实执行了Redis命令(如redisTemplate.opsForValue().set("key", "value"))
  • 若设置了延迟阈值,需确保命令耗时超过阈值才会触发事件,可暂时将阈值设为0以验证:
// 在ClientResources配置中修改阈值
.commandLatencyRecorder(new DefaultCommandLatencyRecorder(Duration.ZERO, Duration.ZERO))

版本兼容性提示

你的Lettuce 6.2.6.RELEASE与Redis 6.2.10版本兼容,无需调整版本,重点排查配置绑定逻辑。

内容的提问来源于stack exchange,提问作者Varid Vaya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 07:57:20