From a650299a2b095cfa7a7a0a9b2d23deb2d70330df Mon Sep 17 00:00:00 2001 From: Null Date: Wed, 12 May 2021 22:11:17 +0800 Subject: [PATCH] Fix RabbitMQ connection was closed unexpectedly. (#863) * Fix RabbitMQ connection was closed unexpectedly. * Ensure that the RabbitMQ connection is unique. --- .../IConnectionChannelPool.Default.cs | 13 +++++++++---- .../RabbitMQConsumerClient.cs | 3 ++- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/src/DotNetCore.CAP.RabbitMQ/IConnectionChannelPool.Default.cs b/src/DotNetCore.CAP.RabbitMQ/IConnectionChannelPool.Default.cs index 32af2de..f3f9474 100644 --- a/src/DotNetCore.CAP.RabbitMQ/IConnectionChannelPool.Default.cs +++ b/src/DotNetCore.CAP.RabbitMQ/IConnectionChannelPool.Default.cs @@ -67,13 +67,17 @@ namespace DotNetCore.CAP.RabbitMQ public IConnection GetConnection() { - if (_connection != null && _connection.IsOpen) + lock (SLock) { + if (_connection != null && _connection.IsOpen) + { + return _connection; + } + + _connection?.Dispose(); + _connection = _connectionActivator(); return _connection; } - - _connection = _connectionActivator(); - return _connection; } public void Dispose() @@ -84,6 +88,7 @@ namespace DotNetCore.CAP.RabbitMQ { context.Dispose(); } + _connection?.Dispose(); } private static Func CreateConnection(RabbitMQOptions options) diff --git a/src/DotNetCore.CAP.RabbitMQ/RabbitMQConsumerClient.cs b/src/DotNetCore.CAP.RabbitMQ/RabbitMQConsumerClient.cs index 8e4d5d4..7115198 100644 --- a/src/DotNetCore.CAP.RabbitMQ/RabbitMQConsumerClient.cs +++ b/src/DotNetCore.CAP.RabbitMQ/RabbitMQConsumerClient.cs @@ -92,7 +92,8 @@ namespace DotNetCore.CAP.RabbitMQ public void Dispose() { _channel?.Dispose(); - _connection?.Dispose(); + //The connection should not be closed here, because the connection is still in use elsewhere. + //_connection?.Dispose(); } public void Connect()