Refactor Payment Api eventbus using CAP

This commit is contained in:
Savorboard 2019-03-14 14:40:43 +08:00
parent 5914c9d606
commit dd7c7d78e1
6 changed files with 57 additions and 127 deletions

View File

@ -1,22 +1,21 @@
namespace Payment.API.IntegrationEvents.EventHandling using DotNetCore.CAP;
namespace Payment.API.IntegrationEvents.EventHandling
{ {
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Abstractions;
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Events;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using Payment.API.IntegrationEvents.Events; using Payment.API.IntegrationEvents.Events;
using Serilog.Context; using Serilog.Context;
using System.Threading.Tasks; using System.Threading.Tasks;
public class OrderStatusChangedToStockConfirmedIntegrationEventHandler : public class OrderStatusChangedToStockConfirmedIntegrationEventHandler : ICapSubscribe
IIntegrationEventHandler<OrderStatusChangedToStockConfirmedIntegrationEvent>
{ {
private readonly IEventBus _eventBus; private readonly ICapPublisher _eventBus;
private readonly PaymentSettings _settings; private readonly PaymentSettings _settings;
private readonly ILogger<OrderStatusChangedToStockConfirmedIntegrationEventHandler> _logger; private readonly ILogger<OrderStatusChangedToStockConfirmedIntegrationEventHandler> _logger;
public OrderStatusChangedToStockConfirmedIntegrationEventHandler( public OrderStatusChangedToStockConfirmedIntegrationEventHandler(
IEventBus eventBus, ICapPublisher eventBus,
IOptionsSnapshot<PaymentSettings> settings, IOptionsSnapshot<PaymentSettings> settings,
ILogger<OrderStatusChangedToStockConfirmedIntegrationEventHandler> logger) ILogger<OrderStatusChangedToStockConfirmedIntegrationEventHandler> logger)
{ {
@ -25,13 +24,12 @@
_logger = logger ?? throw new System.ArgumentNullException(nameof(logger)); _logger = logger ?? throw new System.ArgumentNullException(nameof(logger));
} }
//TODO: [CapSubscribe(nameof(OrderStatusChangedToStockConfirmedIntegrationEvent))]
public async Task Handle(OrderStatusChangedToStockConfirmedIntegrationEvent @event) public async Task Handle(OrderStatusChangedToStockConfirmedIntegrationEvent @event)
{ {
using (LogContext.PushProperty("IntegrationEventContext", $"{@event.Id}-{Program.AppName}")) using (LogContext.PushProperty("IntegrationEventContext", $"{Program.AppName}"))
{ {
_logger.LogInformation("----- Handling integration event: {IntegrationEventId} at {AppName} - ({@IntegrationEvent})", @event.Id, Program.AppName, @event); _logger.LogInformation("----- Handling integration event: {AppName} - ({@IntegrationEvent})", Program.AppName, @event);
IntegrationEvent orderPaymentIntegrationEvent;
//Business feature comment: //Business feature comment:
// When OrderStatusChangedToStockConfirmed Integration Event is handled. // When OrderStatusChangedToStockConfirmed Integration Event is handled.
@ -41,18 +39,16 @@
if (_settings.PaymentSucceded) if (_settings.PaymentSucceded)
{ {
orderPaymentIntegrationEvent = new OrderPaymentSuccededIntegrationEvent(@event.OrderId); var orderPaymentSucceededIntegrationEvent = new OrderPaymentSuccededIntegrationEvent(@event.OrderId);
await _eventBus.PublishAsync(nameof(OrderPaymentSuccededIntegrationEvent), orderPaymentSucceededIntegrationEvent);
_logger.LogInformation("----- Publishing integration event: {AppName} - ({@IntegrationEvent})", Program.AppName, orderPaymentSucceededIntegrationEvent);
} }
else else
{ {
orderPaymentIntegrationEvent = new OrderPaymentFailedIntegrationEvent(@event.OrderId); var orderPaymentFailedIntegrationEvent = new OrderPaymentFailedIntegrationEvent(@event.OrderId);
await _eventBus.PublishAsync(nameof(OrderPaymentFailedIntegrationEvent), orderPaymentFailedIntegrationEvent);
_logger.LogInformation("----- Publishing integration event: {AppName} - ({@IntegrationEvent})", Program.AppName, orderPaymentFailedIntegrationEvent);
} }
_logger.LogInformation("----- Publishing integration event: {IntegrationEventId} from {AppName} - ({@IntegrationEvent})", orderPaymentIntegrationEvent.Id, Program.AppName, orderPaymentIntegrationEvent);
_eventBus.Publish(orderPaymentIntegrationEvent);
await Task.CompletedTask;
} }
} }
} }

View File

@ -1,8 +1,6 @@
namespace Payment.API.IntegrationEvents.Events namespace Payment.API.IntegrationEvents.Events
{ {
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Events; public class OrderPaymentFailedIntegrationEvent
public class OrderPaymentFailedIntegrationEvent : IntegrationEvent
{ {
public int OrderId { get; } public int OrderId { get; }

View File

@ -1,8 +1,6 @@
namespace Payment.API.IntegrationEvents.Events namespace Payment.API.IntegrationEvents.Events
{ {
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Events; public class OrderPaymentSuccededIntegrationEvent
public class OrderPaymentSuccededIntegrationEvent : IntegrationEvent
{ {
public int OrderId { get; } public int OrderId { get; }

View File

@ -1,8 +1,6 @@
namespace Payment.API.IntegrationEvents.Events namespace Payment.API.IntegrationEvents.Events
{ {
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Events; public class OrderStatusChangedToStockConfirmedIntegrationEvent
public class OrderStatusChangedToStockConfirmedIntegrationEvent : IntegrationEvent
{ {
public int OrderId { get; } public int OrderId { get; }

View File

@ -11,6 +11,10 @@
<PackageReference Include="AspNetCore.HealthChecks.Rabbitmq" Version="2.2.0" /> <PackageReference Include="AspNetCore.HealthChecks.Rabbitmq" Version="2.2.0" />
<PackageReference Include="AspNetCore.HealthChecks.UI.Client" Version="2.2.2" /> <PackageReference Include="AspNetCore.HealthChecks.UI.Client" Version="2.2.2" />
<PackageReference Include="Autofac.Extensions.DependencyInjection" Version="4.2.1" /> <PackageReference Include="Autofac.Extensions.DependencyInjection" Version="4.2.1" />
<PackageReference Include="DotNetCore.CAP" Version="2.5.0-preview-69210974" />
<PackageReference Include="DotNetCore.CAP.AzureServiceBus" Version="2.5.0-preview-69210974" />
<PackageReference Include="DotNetCore.CAP.RabbitMQ" Version="2.5.0-preview-69210974" />
<PackageReference Include="DotNetCore.CAP.InMemoryStorage" Version="2.5.0-preview-69210974" />
<PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.2.1" /> <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.2.1" />
<PackageReference Include="Microsoft.ApplicationInsights.DependencyCollector" Version="2.6.1" /> <PackageReference Include="Microsoft.ApplicationInsights.DependencyCollector" Version="2.6.1" />
<PackageReference Include="Microsoft.ApplicationInsights.Kubernetes" Version="1.0.2" /> <PackageReference Include="Microsoft.ApplicationInsights.Kubernetes" Version="1.0.2" />
@ -25,11 +29,5 @@
<PackageReference Include="Serilog.Sinks.Console" Version="3.1.1" /> <PackageReference Include="Serilog.Sinks.Console" Version="3.1.1" />
<PackageReference Include="Serilog.Sinks.Seq" Version="4.0.0" /> <PackageReference Include="Serilog.Sinks.Seq" Version="4.0.0" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\BuildingBlocks\EventBus\EventBusRabbitMQ\EventBusRabbitMQ.csproj" />
<ProjectReference Include="..\..\..\BuildingBlocks\EventBus\EventBusServiceBus\EventBusServiceBus.csproj" />
<ProjectReference Include="..\..\..\BuildingBlocks\EventBus\EventBus\EventBus.csproj" />
<ProjectReference Include="..\..\..\BuildingBlocks\EventBus\IntegrationEventLogEF\IntegrationEventLogEF.csproj" />
</ItemGroup>
</Project> </Project>

View File

@ -4,17 +4,10 @@ using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.ApplicationInsights.ServiceFabric; using Microsoft.ApplicationInsights.ServiceFabric;
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting;
using Microsoft.Azure.ServiceBus;
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus;
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Abstractions;
using Microsoft.eShopOnContainers.BuildingBlocks.EventBusRabbitMQ;
using Microsoft.eShopOnContainers.BuildingBlocks.EventBusServiceBus;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Payment.API.IntegrationEvents.EventHandling; using Payment.API.IntegrationEvents.EventHandling;
using Payment.API.IntegrationEvents.Events;
using RabbitMQ.Client;
using System; using System;
using HealthChecks.UI.Client; using HealthChecks.UI.Client;
using Microsoft.AspNetCore.Diagnostics.HealthChecks; using Microsoft.AspNetCore.Diagnostics.HealthChecks;
@ -39,49 +32,40 @@ namespace Payment.API
RegisterAppInsights(services); RegisterAppInsights(services);
if (Configuration.GetValue<bool>("AzureServiceBusEnabled")) services.AddIntegrationEventHandler();
services.AddCap(options =>
{ {
services.AddSingleton<IServiceBusPersisterConnection>(sp => options.UseInMemoryStorage();
if (Configuration.GetValue<bool>("AzureServiceBusEnabled"))
{ {
var logger = sp.GetRequiredService<ILogger<DefaultServiceBusPersisterConnection>>(); options.UseAzureServiceBus(Configuration["EventBusConnection"]);
}
var serviceBusConnectionString = Configuration["EventBusConnection"]; else
var serviceBusConnection = new ServiceBusConnectionStringBuilder(serviceBusConnectionString);
return new DefaultServiceBusPersisterConnection(serviceBusConnection, logger);
});
}
else
{
services.AddSingleton<IRabbitMQPersistentConnection>(sp =>
{ {
var logger = sp.GetRequiredService<ILogger<DefaultRabbitMQPersistentConnection>>(); options.UseRabbitMQ(conf =>
var factory = new ConnectionFactory()
{ {
HostName = Configuration["EventBusConnection"] conf.HostName = Configuration["EventBusConnection"];
}; if (!string.IsNullOrEmpty(Configuration["EventBusUserName"]))
{
conf.UserName = Configuration["EventBusUserName"];
}
if (!string.IsNullOrEmpty(Configuration["EventBusPassword"]))
{
conf.Password = Configuration["EventBusPassword"];
}
});
}
if (!string.IsNullOrEmpty(Configuration["EventBusUserName"])) if (!string.IsNullOrEmpty(Configuration["EventBusRetryCount"]))
{ {
factory.UserName = Configuration["EventBusUserName"]; options.FailedRetryCount = int.Parse(Configuration["EventBusRetryCount"]);
} }
if (!string.IsNullOrEmpty(Configuration["EventBusPassword"])) if (!string.IsNullOrEmpty(Configuration["SubscriptionClientName"]))
{ {
factory.Password = Configuration["EventBusPassword"]; options.DefaultGroup = Configuration["SubscriptionClientName"];
} }
});
var retryCount = 5;
if (!string.IsNullOrEmpty(Configuration["EventBusRetryCount"]))
{
retryCount = int.Parse(Configuration["EventBusRetryCount"]);
}
return new DefaultRabbitMQPersistentConnection(factory, logger, retryCount);
});
}
RegisterEventBus(services);
var container = new ContainerBuilder(); var container = new ContainerBuilder();
container.Populate(services); container.Populate(services);
@ -111,8 +95,6 @@ namespace Payment.API
{ {
Predicate = r => r.Name.Contains("self") Predicate = r => r.Name.Contains("self")
}); });
ConfigureEventBus(app);
} }
private void RegisterAppInsights(IServiceCollection services) private void RegisterAppInsights(IServiceCollection services)
@ -132,56 +114,16 @@ namespace Payment.API
new FabricTelemetryInitializer()); new FabricTelemetryInitializer());
} }
} }
private void RegisterEventBus(IServiceCollection services)
{
var subscriptionClientName = Configuration["SubscriptionClientName"];
if (Configuration.GetValue<bool>("AzureServiceBusEnabled"))
{
services.AddSingleton<IEventBus, EventBusServiceBus>(sp =>
{
var serviceBusPersisterConnection = sp.GetRequiredService<IServiceBusPersisterConnection>();
var iLifetimeScope = sp.GetRequiredService<ILifetimeScope>();
var logger = sp.GetRequiredService<ILogger<EventBusServiceBus>>();
var eventBusSubcriptionsManager = sp.GetRequiredService<IEventBusSubscriptionsManager>();
return new EventBusServiceBus(serviceBusPersisterConnection, logger,
eventBusSubcriptionsManager, subscriptionClientName, iLifetimeScope);
});
}
else
{
services.AddSingleton<IEventBus, EventBusRabbitMQ>(sp =>
{
var rabbitMQPersistentConnection = sp.GetRequiredService<IRabbitMQPersistentConnection>();
var iLifetimeScope = sp.GetRequiredService<ILifetimeScope>();
var logger = sp.GetRequiredService<ILogger<EventBusRabbitMQ>>();
var eventBusSubcriptionsManager = sp.GetRequiredService<IEventBusSubscriptionsManager>();
var retryCount = 5;
if (!string.IsNullOrEmpty(Configuration["EventBusRetryCount"]))
{
retryCount = int.Parse(Configuration["EventBusRetryCount"]);
}
return new EventBusRabbitMQ(rabbitMQPersistentConnection, logger, iLifetimeScope, eventBusSubcriptionsManager, subscriptionClientName, retryCount);
});
}
services.AddTransient<OrderStatusChangedToStockConfirmedIntegrationEventHandler>();
services.AddSingleton<IEventBusSubscriptionsManager, InMemoryEventBusSubscriptionsManager>();
}
private void ConfigureEventBus(IApplicationBuilder app)
{
var eventBus = app.ApplicationServices.GetRequiredService<IEventBus>();
eventBus.Subscribe<OrderStatusChangedToStockConfirmedIntegrationEvent, OrderStatusChangedToStockConfirmedIntegrationEventHandler>();
}
} }
public static class CustomExtensionMethods public static class CustomExtensionMethods
{ {
public static IServiceCollection AddIntegrationEventHandler(this IServiceCollection services)
{
services.AddTransient<OrderStatusChangedToStockConfirmedIntegrationEventHandler>(); //Subscribe for OrderStatusChangedToStockConfirmedIntegrationEvent
return services;
}
public static IServiceCollection AddCustomHealthCheck(this IServiceCollection services, IConfiguration configuration) public static IServiceCollection AddCustomHealthCheck(this IServiceCollection services, IConfiguration configuration)
{ {
var hcBuilder = services.AddHealthChecks(); var hcBuilder = services.AddHealthChecks();