From 51453d502bc83d1443b42dff86072c5be999501d Mon Sep 17 00:00:00 2001 From: Savorboard Date: Tue, 11 Jun 2024 21:14:39 +0800 Subject: [PATCH] Try to fix NATS reconnection publish issue after restarting server. #1542 --- src/DotNetCore.CAP.NATS/CAP.NATSOptions.cs | 2 +- src/DotNetCore.CAP.NATS/DotNetCore.CAP.NATS.csproj | 2 +- src/DotNetCore.CAP.NATS/IConnectionPool.Default.cs | 9 ++++++--- 3 files changed, 8 insertions(+), 5 deletions(-) diff --git a/src/DotNetCore.CAP.NATS/CAP.NATSOptions.cs b/src/DotNetCore.CAP.NATS/CAP.NATSOptions.cs index 1b9ed71e4..b35a718e1 100644 --- a/src/DotNetCore.CAP.NATS/CAP.NATSOptions.cs +++ b/src/DotNetCore.CAP.NATS/CAP.NATSOptions.cs @@ -18,7 +18,7 @@ public class NATSOptions /// Gets or sets the server url/urls used to connect to the NATs server. /// /// This may contain username/password information. - public string Servers { get; set; } = "nats://localhost:4222"; + public string Servers { get; set; } = "nats://127.0.0.1:4222"; /// /// connection pool size, default is 10 diff --git a/src/DotNetCore.CAP.NATS/DotNetCore.CAP.NATS.csproj b/src/DotNetCore.CAP.NATS/DotNetCore.CAP.NATS.csproj index f7fae3e6f..192463c66 100644 --- a/src/DotNetCore.CAP.NATS/DotNetCore.CAP.NATS.csproj +++ b/src/DotNetCore.CAP.NATS/DotNetCore.CAP.NATS.csproj @@ -7,7 +7,7 @@ - + diff --git a/src/DotNetCore.CAP.NATS/IConnectionPool.Default.cs b/src/DotNetCore.CAP.NATS/IConnectionPool.Default.cs index a9d403505..361b959a7 100644 --- a/src/DotNetCore.CAP.NATS/IConnectionPool.Default.cs +++ b/src/DotNetCore.CAP.NATS/IConnectionPool.Default.cs @@ -14,6 +14,7 @@ public class ConnectionPool : IConnectionPool, IDisposable { private readonly NATSOptions _options; private readonly ConcurrentQueue _connectionPool; + private readonly ConnectionFactory _connectionFactory; private int _pCount; private int _maxSize; @@ -54,14 +55,17 @@ public IConnection RentConnection() public bool Return(IConnection connection) { - if (Interlocked.Increment(ref _pCount) <= _maxSize) + if (Interlocked.Increment(ref _pCount) <= _maxSize && connection.State == ConnState.CONNECTED) { _connectionPool.Enqueue(connection); return true; } - connection.Dispose(); + if (!connection.IsReconnecting()) + { + connection.Dispose(); + } Interlocked.Decrement(ref _pCount); @@ -75,7 +79,6 @@ public void Dispose() while (_connectionPool.TryDequeue(out var context)) { context.Dispose(); - } } }