问题描述

在Java应用中,使用 Lettuce 作为客户端SDK与Azure Redis 服务连接,当遇见连接断开后,长达15分钟才会重连。导致应用在长达15分的时间,持续报错Timeout

 

问题解答

这是 Lettuce 目前的一个未解决的已知问题,可以查看此 github issue来了解这个问题的背景:

  1. https://github.com/StackExchange/StackExchange.Redis/issues/1848 (Connection does not re-establish for 15 minutes when running on Linux #1848)
  2. https://github.com/lettuce-io/lettuce-core/issues/2082 ( Add support for disconnect on timeout to recover early from no RST packet failures #2082) 

问题根源是 在于在某些时候Redis服务或者客户端由于网络原因等断掉TCP连接后,Lettuce会等待TCP重试15之后才丢弃该连接(重试15次是和操作系统 tcp_retries2 的配置有关),然后创建新的TCP连接,因此 Lettuce 不会立即重连而是等待15分钟后进行重连,造成了超时。

 

所以可以通过使用其他Redis的SDK来代替Lettuce(如 Jedis)。或者是根据微软官方文档介绍,修改Linux系统中的 tcp_retries2 参数值 (net.ipv4.tcp_retries2  为 5)。 

 

(参考:https://docs.azure.cn/zh-cn/azure-cache-for-redis/cache-best-practices-connection#tcp-settings-for-linux-hosted-client-applications

 

可以通过以下的代码来复现 "Lettuce在Linux系统上超时15分钟" 问题

测试代码:

public class Main {
    public static void main(String[] args) {
        RedisClient client = RedisClient.create(RedisURI.Builder.redis("redis-hostname", 6379)
                .withSsl(false)
                .withPassword("xxxxxx")
                // .withTimeout(Duration.ofSeconds(10))
                .build());
        client.setOptions(ClientOptions.builder()
                // .socketOptions(socketOptions)
                .autoReconnect(true)
                .disconnectedBehavior(ClientOptions.DisconnectedBehavior.DEFAULT)
                .build());

        RedisCommands<String, String> sync = client.connect().sync();

        for (int i = 0; i < 1000; i++) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            try {
                System.out.println("========" + i);
                sync.set("" + i, "" + i);

            } catch (Exception e) {
                System.out.println("eeeeeeee" + e.getMessage());
            }
        }
    }
}

首先,将程序在Linux服务器运行,程序会循环往Redis Set一些值。

然后,人为操作,对Azure Redis进行重启操作。

最后,可以发现Lettuce客户端会持续Timeout,直到大约15分钟后才会和Redis进行重新连接。

 

 

参考资料

Azure Redis有关连接复原的最佳做法:https://docs.azure.cn/zh-cn/azure-cache-for-redis/cache-best-practices-connection#tcp-settings-for-linux-hosted-client-applications