Code re-factorings and formatting in EventBus.ServiceBus project

This commit is contained in:
Rafsanul Hasan 2018-09-09 05:17:33 +06:00
parent db13fa6091
commit 0705dc0ab5
No known key found for this signature in database
GPG Key ID: FC57FD2D87BE60DD
3 changed files with 219 additions and 213 deletions

View File

@ -1,44 +1,48 @@
using Microsoft.Azure.ServiceBus; using Microsoft.Azure.ServiceBus;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using System;
namespace Microsoft.eShopOnContainers.BuildingBlocks.EventBusServiceBus namespace Microsoft.eShopOnContainers.BuildingBlocks.EventBusServiceBus
{ {
public class DefaultServiceBusPersisterConnection :IServiceBusPersisterConnection using ArgumentNullException = System.ArgumentNullException;
{
private readonly ILogger<DefaultServiceBusPersisterConnection> _logger;
private readonly ServiceBusConnectionStringBuilder _serviceBusConnectionStringBuilder;
private ITopicClient _topicClient;
bool _disposed; public class DefaultServiceBusPersisterConnection : IServiceBusPersisterConnection
{
private readonly ILogger<DefaultServiceBusPersisterConnection> _logger;
private readonly ServiceBusConnectionStringBuilder _serviceBusConnectionStringBuilder;
private ITopicClient _topicClient;
public DefaultServiceBusPersisterConnection(ServiceBusConnectionStringBuilder serviceBusConnectionStringBuilder, bool _disposed;
ILogger<DefaultServiceBusPersisterConnection> logger)
{
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_serviceBusConnectionStringBuilder = serviceBusConnectionStringBuilder ??
throw new ArgumentNullException(nameof(serviceBusConnectionStringBuilder));
_topicClient = new TopicClient(_serviceBusConnectionStringBuilder, RetryPolicy.Default);
}
public ServiceBusConnectionStringBuilder ServiceBusConnectionStringBuilder => _serviceBusConnectionStringBuilder; public DefaultServiceBusPersisterConnection(ServiceBusConnectionStringBuilder serviceBusConnectionStringBuilder,
ILogger<DefaultServiceBusPersisterConnection> logger)
{
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
public ITopicClient CreateModel() _serviceBusConnectionStringBuilder = serviceBusConnectionStringBuilder ??
{ throw new ArgumentNullException(nameof(serviceBusConnectionStringBuilder));
if(_topicClient.IsClosedOrClosing) _topicClient = new TopicClient(_serviceBusConnectionStringBuilder, RetryPolicy.Default);
{ }
_topicClient = new TopicClient(_serviceBusConnectionStringBuilder, RetryPolicy.Default);
}
return _topicClient; public ServiceBusConnectionStringBuilder ServiceBusConnectionStringBuilder => _serviceBusConnectionStringBuilder;
}
public void Dispose() public ITopicClient CreateModel()
{ {
if (_disposed) return; if (_topicClient.IsClosedOrClosing)
{
_topicClient = new TopicClient(_serviceBusConnectionStringBuilder, RetryPolicy.Default);
}
_disposed = true; return _topicClient;
} }
}
public void Dispose()
{
if (_disposed)
{
return;
}
_disposed = true;
}
}
} }

View File

@ -1,199 +1,199 @@
namespace Microsoft.eShopOnContainers.BuildingBlocks.EventBusServiceBus namespace Microsoft.eShopOnContainers.BuildingBlocks.EventBusServiceBus
{ {
using Autofac; using Autofac;
using Microsoft.Azure.ServiceBus; using Microsoft.Azure.ServiceBus;
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus; using Microsoft.eShopOnContainers.BuildingBlocks.EventBus;
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Abstractions; using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Abstractions;
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Events; using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Events;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Newtonsoft.Json; using Newtonsoft.Json;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
using System; using System;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
public class EventBusServiceBus : IEventBus public class EventBusServiceBus : IEventBus
{ {
private readonly IServiceBusPersisterConnection _serviceBusPersisterConnection; private readonly IServiceBusPersisterConnection _serviceBusPersisterConnection;
private readonly ILogger<EventBusServiceBus> _logger; private readonly ILogger<EventBusServiceBus> _logger;
private readonly IEventBusSubscriptionsManager _subsManager; private readonly IEventBusSubscriptionsManager _subsManager;
private readonly SubscriptionClient _subscriptionClient; private readonly SubscriptionClient _subscriptionClient;
private readonly ILifetimeScope _autofac; private readonly ILifetimeScope _autofac;
private readonly string AUTOFAC_SCOPE_NAME = "eshop_event_bus"; private readonly string AUTOFAC_SCOPE_NAME = "eshop_event_bus";
private const string INTEGRATION_EVENT_SUFIX = "IntegrationEvent"; private const string INTEGRATION_EVENT_SUFIX = "IntegrationEvent";
public EventBusServiceBus(IServiceBusPersisterConnection serviceBusPersisterConnection, public EventBusServiceBus(IServiceBusPersisterConnection serviceBusPersisterConnection,
ILogger<EventBusServiceBus> logger, IEventBusSubscriptionsManager subsManager, string subscriptionClientName, ILogger<EventBusServiceBus> logger, IEventBusSubscriptionsManager subsManager, string subscriptionClientName,
ILifetimeScope autofac) ILifetimeScope autofac)
{ {
_serviceBusPersisterConnection = serviceBusPersisterConnection; _serviceBusPersisterConnection = serviceBusPersisterConnection;
_logger = logger; _logger = logger;
_subsManager = subsManager ?? new InMemoryEventBusSubscriptionsManager(); _subsManager = subsManager ?? new InMemoryEventBusSubscriptionsManager();
_subscriptionClient = new SubscriptionClient(serviceBusPersisterConnection.ServiceBusConnectionStringBuilder, _subscriptionClient = new SubscriptionClient(serviceBusPersisterConnection.ServiceBusConnectionStringBuilder,
subscriptionClientName); subscriptionClientName);
_autofac = autofac; _autofac = autofac;
RemoveDefaultRule(); RemoveDefaultRule();
RegisterSubscriptionClientMessageHandler(); RegisterSubscriptionClientMessageHandler();
} }
public void Publish(IntegrationEvent @event) public void Publish(IntegrationEvent @event)
{ {
var eventName = @event.GetType().Name.Replace(INTEGRATION_EVENT_SUFIX, ""); var eventName = @event.GetType().Name.Replace(INTEGRATION_EVENT_SUFIX, "");
var jsonMessage = JsonConvert.SerializeObject(@event); var jsonMessage = JsonConvert.SerializeObject(@event);
var body = Encoding.UTF8.GetBytes(jsonMessage); var body = Encoding.UTF8.GetBytes(jsonMessage);
var message = new Message var message = new Message
{ {
MessageId = Guid.NewGuid().ToString(), MessageId = Guid.NewGuid().ToString(),
Body = body, Body = body,
Label = eventName, Label = eventName,
}; };
var topicClient = _serviceBusPersisterConnection.CreateModel(); var topicClient = _serviceBusPersisterConnection.CreateModel();
topicClient.SendAsync(message) topicClient.SendAsync(message)
.GetAwaiter() .GetAwaiter()
.GetResult(); .GetResult();
} }
public void SubscribeDynamic<TH>(string eventName) public void SubscribeDynamic<TH>(string eventName)
where TH : IDynamicIntegrationEventHandler where TH : IDynamicIntegrationEventHandler
{ {
_subsManager.AddDynamicSubscription<TH>(eventName); _subsManager.AddDynamicSubscription<TH>(eventName);
} }
public void Subscribe<T, TH>() public void Subscribe<T, TH>()
where T : IntegrationEvent where T : IntegrationEvent
where TH : IIntegrationEventHandler<T> where TH : IIntegrationEventHandler<T>
{ {
var eventName = typeof(T).Name.Replace(INTEGRATION_EVENT_SUFIX, ""); var eventName = typeof(T).Name.Replace(INTEGRATION_EVENT_SUFIX, "");
var containsKey = _subsManager.HasSubscriptionsForEvent<T>(); var containsKey = _subsManager.HasSubscriptionsForEvent<T>();
if (!containsKey) if (!containsKey)
{ {
try try
{ {
_subscriptionClient.AddRuleAsync(new RuleDescription _subscriptionClient.AddRuleAsync(new RuleDescription
{ {
Filter = new CorrelationFilter { Label = eventName }, Filter = new CorrelationFilter { Label = eventName },
Name = eventName Name = eventName
}).GetAwaiter().GetResult(); }).GetAwaiter().GetResult();
} }
catch (ServiceBusException) catch (ServiceBusException)
{ {
_logger.LogInformation($"The messaging entity {eventName} already exists."); _logger.LogInformation($"The messaging entity {eventName} already exists.");
} }
} }
_subsManager.AddSubscription<T, TH>(); _subsManager.AddSubscription<T, TH>();
} }
public void Unsubscribe<T, TH>() public void Unsubscribe<T, TH>()
where T : IntegrationEvent where T : IntegrationEvent
where TH : IIntegrationEventHandler<T> where TH : IIntegrationEventHandler<T>
{ {
var eventName = typeof(T).Name.Replace(INTEGRATION_EVENT_SUFIX, ""); var eventName = typeof(T).Name.Replace(INTEGRATION_EVENT_SUFIX, "");
try try
{ {
_subscriptionClient _subscriptionClient
.RemoveRuleAsync(eventName) .RemoveRuleAsync(eventName)
.GetAwaiter() .GetAwaiter()
.GetResult(); .GetResult();
} }
catch (MessagingEntityNotFoundException) catch (MessagingEntityNotFoundException)
{ {
_logger.LogInformation($"The messaging entity {eventName} Could not be found."); _logger.LogInformation($"The messaging entity {eventName} Could not be found.");
} }
_subsManager.RemoveSubscription<T, TH>(); _subsManager.RemoveSubscription<T, TH>();
} }
public void UnsubscribeDynamic<TH>(string eventName) public void UnsubscribeDynamic<TH>(string eventName)
where TH : IDynamicIntegrationEventHandler where TH : IDynamicIntegrationEventHandler
{ {
_subsManager.RemoveDynamicSubscription<TH>(eventName); _subsManager.RemoveDynamicSubscription<TH>(eventName);
} }
public void Dispose() public void Dispose()
{ {
_subsManager.Clear(); _subsManager.Clear();
} }
private void RegisterSubscriptionClientMessageHandler() private void RegisterSubscriptionClientMessageHandler()
{ {
_subscriptionClient.RegisterMessageHandler( _subscriptionClient.RegisterMessageHandler(
async (message, token) => async (message, token) =>
{ {
var eventName = $"{message.Label}{INTEGRATION_EVENT_SUFIX}"; var eventName = $"{message.Label}{INTEGRATION_EVENT_SUFIX}";
var messageData = Encoding.UTF8.GetString(message.Body); var messageData = Encoding.UTF8.GetString(message.Body);
// Complete the message so that it is not received again. // Complete the message so that it is not received again.
if (await ProcessEvent(eventName, messageData)) if (await ProcessEvent(eventName, messageData))
{ {
await _subscriptionClient.CompleteAsync(message.SystemProperties.LockToken); await _subscriptionClient.CompleteAsync(message.SystemProperties.LockToken);
} }
}, },
new MessageHandlerOptions(ExceptionReceivedHandler) { MaxConcurrentCalls = 10, AutoComplete = false }); new MessageHandlerOptions(ExceptionReceivedHandler) { MaxConcurrentCalls = 10, AutoComplete = false });
} }
private Task ExceptionReceivedHandler(ExceptionReceivedEventArgs exceptionReceivedEventArgs) private Task ExceptionReceivedHandler(ExceptionReceivedEventArgs exceptionReceivedEventArgs)
{ {
Console.WriteLine($"Message handler encountered an exception {exceptionReceivedEventArgs.Exception}."); Console.WriteLine($"Message handler encountered an exception {exceptionReceivedEventArgs.Exception}.");
var context = exceptionReceivedEventArgs.ExceptionReceivedContext; var context = exceptionReceivedEventArgs.ExceptionReceivedContext;
Console.WriteLine("Exception context for troubleshooting:"); Console.WriteLine("Exception context for troubleshooting:");
Console.WriteLine($"- Endpoint: {context.Endpoint}"); Console.WriteLine($"- Endpoint: {context.Endpoint}");
Console.WriteLine($"- Entity Path: {context.EntityPath}"); Console.WriteLine($"- Entity Path: {context.EntityPath}");
Console.WriteLine($"- Executing Action: {context.Action}"); Console.WriteLine($"- Executing Action: {context.Action}");
return Task.CompletedTask; return Task.CompletedTask;
} }
private async Task<bool> ProcessEvent(string eventName, string message) private async Task<bool> ProcessEvent(string eventName, string message)
{ {
var processed = false; var processed = false;
if (_subsManager.HasSubscriptionsForEvent(eventName)) if (_subsManager.HasSubscriptionsForEvent(eventName))
{ {
using (var scope = _autofac.BeginLifetimeScope(AUTOFAC_SCOPE_NAME)) using (var scope = _autofac.BeginLifetimeScope(AUTOFAC_SCOPE_NAME))
{ {
var subscriptions = _subsManager.GetHandlersForEvent(eventName); var subscriptions = _subsManager.GetHandlersForEvent(eventName);
foreach (var subscription in subscriptions) foreach (var subscription in subscriptions)
{ {
if (subscription.IsDynamic) if (subscription.IsDynamic)
{ {
var handler = scope.ResolveOptional(subscription.HandlerType) as IDynamicIntegrationEventHandler; var handler = scope.ResolveOptional(subscription.HandlerType) as IDynamicIntegrationEventHandler;
dynamic eventData = JObject.Parse(message); dynamic eventData = JObject.Parse(message);
await handler.Handle(eventData); await handler.Handle(eventData);
} }
else else
{ {
var eventType = _subsManager.GetEventTypeByName(eventName); var eventType = _subsManager.GetEventTypeByName(eventName);
var integrationEvent = JsonConvert.DeserializeObject(message, eventType); var integrationEvent = JsonConvert.DeserializeObject(message, eventType);
var handler = scope.ResolveOptional(subscription.HandlerType); var handler = scope.ResolveOptional(subscription.HandlerType);
var concreteType = typeof(IIntegrationEventHandler<>).MakeGenericType(eventType); var concreteType = typeof(IIntegrationEventHandler<>).MakeGenericType(eventType);
await (Task)concreteType.GetMethod("Handle").Invoke(handler, new object[] { integrationEvent }); await (Task)concreteType.GetMethod("Handle").Invoke(handler, new object[] { integrationEvent });
} }
} }
} }
processed = true; processed = true;
} }
return processed; return processed;
} }
private void RemoveDefaultRule() private void RemoveDefaultRule()
{ {
try try
{ {
_subscriptionClient _subscriptionClient
.RemoveRuleAsync(RuleDescription.DefaultRuleName) .RemoveRuleAsync(RuleDescription.DefaultRuleName)
.GetAwaiter() .GetAwaiter()
.GetResult(); .GetResult();
} }
catch (MessagingEntityNotFoundException) catch (MessagingEntityNotFoundException)
{ {
_logger.LogInformation($"The messaging entity { RuleDescription.DefaultRuleName } Could not be found."); _logger.LogInformation($"The messaging entity { RuleDescription.DefaultRuleName } Could not be found.");
} }
} }
} }
} }

View File

@ -1,12 +1,14 @@
namespace Microsoft.eShopOnContainers.BuildingBlocks.EventBusServiceBus using IDisposable = System.IDisposable;
namespace Microsoft.eShopOnContainers.BuildingBlocks.EventBusServiceBus
{ {
using Microsoft.Azure.ServiceBus; using ITopicClient = Azure.ServiceBus.ITopicClient;
using System; using ServiceBusConnectionStringBuilder = Azure.ServiceBus.ServiceBusConnectionStringBuilder;
public interface IServiceBusPersisterConnection : IDisposable public interface IServiceBusPersisterConnection : IDisposable
{ {
ServiceBusConnectionStringBuilder ServiceBusConnectionStringBuilder { get; } ServiceBusConnectionStringBuilder ServiceBusConnectionStringBuilder { get; }
ITopicClient CreateModel(); ITopicClient CreateModel();
} }
} }