-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDefaultRabbitMqConnection.cs
163 lines (124 loc) · 4.52 KB
/
DefaultRabbitMqConnection.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
using System.Net.Sockets;
using Infra.Core.Extensions;
using Infra.EventBus.RabbitMQ.Abstractions;
using Infra.EventBus.RabbitMQ.Configuration;
using Infra.EventBus.RabbitMQ.Configuration.Validators;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Polly;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using RabbitMQ.Client.Exceptions;
namespace Infra.EventBus.RabbitMQ;
public class DefaultRabbitMqConnection : IRabbitMqConnection
{
private readonly ILogger<DefaultRabbitMqConnection> logger;
private readonly ConnectionSettings settings;
private readonly ConnectionFactory connectionFactory;
private readonly object syncRoot = new();
private IConnection connection;
private bool disposed;
#region Properties
public bool IsConnected => connection is { IsOpen: true } && !disposed;
#endregion
#region Constructor
public DefaultRabbitMqConnection(
ILogger<DefaultRabbitMqConnection> logger,
IOptions<ConnectionSettings> settings)
{
this.logger = logger ?? throw new ArgumentNullException(nameof(logger));
this.settings = ConnectionSettingsValidator.TryValidate(settings.Value, out var validationException) ? settings.Value : throw validationException;
connectionFactory = GetConnectionFactory(this.settings);
}
#endregion
public IModel CreateChannel()
{
if (!IsConnected)
throw new InvalidOperationException("No RabbitMQ connections are available to perform this action.");
return connection.CreateModel();
}
public bool TryConnect()
{
logger.Information("RabbitMQ client is trying to connect...");
lock (syncRoot)
{
var policy = Policy.Handle<SocketException>()
.Or<BrokerUnreachableException>()
.WaitAndRetry(settings.RetryCount, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), (ex, time)
=> logger.Warning(ex, $"RabbitMQ client could not connect after {time.TotalSeconds:n1}s. ({ex.Message})"));
policy.Execute(() => connection = connectionFactory.CreateConnection());
if (!IsConnected)
{
logger.Critical("FATAL ERROR: RabbitMQ connections could not be created and opened.");
return false;
}
connection.ConnectionBlocked += OnConnectionBlocked;
connection.CallbackException += OnCallbackException;
connection.ConnectionShutdown += OnConnectionShutdown;
logger.Information($"RabbitMQ client acquired a persistent connection to '{connection.Endpoint.HostName}' and is subscribed to failure events.");
return true;
}
}
#region Private Method
private static ConnectionFactory GetConnectionFactory(ConnectionSettings settings)
{
var factory = new ConnectionFactory
{
HostName = settings.Host,
Port = settings.Port,
DispatchConsumersAsync = true
};
if (!string.IsNullOrEmpty(settings.UserName))
factory.UserName = settings.UserName;
if (!string.IsNullOrEmpty(settings.Password))
factory.Password = settings.Password;
return factory;
}
private void OnConnectionBlocked(object sender, ConnectionBlockedEventArgs e)
{
if (disposed)
return;
logger.Warning("A RabbitMQ connection is blocked. Trying to re-connect...");
TryConnect();
}
private void OnCallbackException(object sender, CallbackExceptionEventArgs e)
{
if (disposed)
return;
logger.Warning("A RabbitMQ connection throw exception. Trying to re-connect...");
TryConnect();
}
private void OnConnectionShutdown(object sender, ShutdownEventArgs reason)
{
if (disposed)
return;
logger.Warning("A RabbitMQ connection is on shutdown. Trying to re-connect...");
TryConnect();
}
#endregion
#region Dispose
~DefaultRabbitMqConnection() => Dispose(false);
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposed)
return;
if (disposing)
{
try
{
connection.Dispose();
}
catch (IOException ex)
{
logger.Critical($"{ex}");
}
}
disposed = true;
}
#endregion
}