0

我有一个应用程序,我使用此扩展方法创建 Stan 连接并将其添加到ServiceProvider.

public static IServiceCollection AddStanClient(this IServiceCollection services, StanSettings settings)
{
    var stanOptions = StanOptions.GetDefaultOptions();
    var natsOptions = ConnectionFactory.GetDefaultOptions();
    var stanClientId = $"{settings.ClientId}-{Guid.NewGuid()}";
    var stanClusterId = settings.ClusterId;

    natsOptions.Servers = settings.NatsServers.ToArray();
    natsOptions.AllowReconnect = true;
    natsOptions.MaxReconnect = Options.ReconnectForever;
    natsOptions.PingInterval = 2000;
    natsOptions.MaxPingsOut = 2;
    natsOptions.ReconnectWait = 1000;
    natsOptions.Timeout = 4000;

    IStanConnection stanConnection = new StanConnectionFactory().CreateConnection(stanClusterId, stanClientId, stanOptions);

    natsOptions.ClosedEventHandler += (object sender, ConnEventArgs arg) =>
            {
                Console.WriteLine($"connection lost on connection {arg.Conn.ConnectedId}" +
                                  $"{Environment.NewLine} {arg.Error.StackTrace}");
            };

    natsOptions.ReconnectedEventHandler += (object sender, ConnEventArgs arg) => {
                stanOptions.NatsConn = arg.Conn; 
                //services.Remove(new ServiceDescriptor(typeof(IStanConnection), stanConnection));
                stanConnection = new StanConnectionFactory().CreateConnection(stanClusterId, stanClientId, stanOptions);

                services.AddSingleton<IStanConnection>(stanConnection);

                Console.WriteLine($"Connection recovered by connection id {arg.Conn.ConnectedId}");
        }; 
            
    stanOptions.NatsConn = new ConnectionFactory().CreateConnection(natsOptions);
    stanOptions.ConnectionLostEventHandler += (object sender, StanConnLostHandlerArgs arg) => {
            Console.WriteLine($"connection lost on connection {arg.Connection.NATSConnection.ConnectedId}" +
            $"{Environment.NewLine} {arg.ConnectionException.StackTrace}"); 
        };
            
    services.AddSingleton<IStanConnection>(stanConnection);

    return services;
}

当它失去与 nats 流服务器的连接 15 秒时,它处于重新连接模式,如果连接再次正常工作,我的应用程序可以毫无问题地发布消息。

但是 15 秒后,我会收到连接关闭错误,并且重新连接到服务器无法解决任何问题,并且我会收到连接关闭错误,直到我重新启动我的应用程序。

nats连接将再次连接但Stan连接无法更新其连接状态可以使事情更加清楚。

我的 stan 客户端版本是 0.3.0。

如何更新此连接或将其配置为在找到服务时重新连接?

4

0 回答 0