Refactor Catalog Api eventbus using CAP
This commit is contained in:
parent
9cf4ade24b
commit
1052527354
@ -40,6 +40,10 @@
|
||||
<PackageReference Include="AspNetCore.HealthChecks.SqlServer" Version="2.2.0" />
|
||||
<PackageReference Include="AspNetCore.HealthChecks.UI.Client" Version="2.2.2" />
|
||||
<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.SQLServer" Version="2.5.0-preview-69210974" />
|
||||
<PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.2.1" />
|
||||
<PackageReference Include="Microsoft.ApplicationInsights.DependencyCollector" Version="2.6.1" />
|
||||
<PackageReference Include="Microsoft.ApplicationInsights.Kubernetes" Version="1.0.2" />
|
||||
@ -58,10 +62,6 @@
|
||||
</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" />
|
||||
<ProjectReference Include="..\..\..\BuildingBlocks\WebHostCustomization\WebHost.Customization\WebHost.Customization.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
|
@ -1,5 +1,4 @@
|
||||
using Catalog.API.IntegrationEvents;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.eShopOnContainers.Services.Catalog.API.Infrastructure;
|
||||
using Microsoft.eShopOnContainers.Services.Catalog.API.IntegrationEvents.Events;
|
||||
@ -11,6 +10,7 @@ using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Threading.Tasks;
|
||||
using DotNetCore.CAP;
|
||||
|
||||
namespace Microsoft.eShopOnContainers.Services.Catalog.API.Controllers
|
||||
{
|
||||
@ -20,12 +20,12 @@ namespace Microsoft.eShopOnContainers.Services.Catalog.API.Controllers
|
||||
{
|
||||
private readonly CatalogContext _catalogContext;
|
||||
private readonly CatalogSettings _settings;
|
||||
private readonly ICatalogIntegrationEventService _catalogIntegrationEventService;
|
||||
private readonly ICapPublisher _eventBus;
|
||||
|
||||
public CatalogController(CatalogContext context, IOptionsSnapshot<CatalogSettings> settings, ICatalogIntegrationEventService catalogIntegrationEventService)
|
||||
public CatalogController(CatalogContext context, IOptionsSnapshot<CatalogSettings> settings, ICapPublisher eventBus)
|
||||
{
|
||||
_catalogContext = context ?? throw new ArgumentNullException(nameof(context));
|
||||
_catalogIntegrationEventService = catalogIntegrationEventService ?? throw new ArgumentNullException(nameof(catalogIntegrationEventService));
|
||||
_eventBus = eventBus ?? throw new ArgumentNullException(nameof(eventBus));
|
||||
_settings = settings.Value;
|
||||
|
||||
context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
|
||||
@ -233,10 +233,10 @@ namespace Microsoft.eShopOnContainers.Services.Catalog.API.Controllers
|
||||
var priceChangedEvent = new ProductPriceChangedIntegrationEvent(catalogItem.Id, productToUpdate.Price, oldPrice);
|
||||
|
||||
// Achieving atomicity between original Catalog database operation and the IntegrationEventLog thanks to a local transaction
|
||||
await _catalogIntegrationEventService.SaveEventAndCatalogContextChangesAsync(priceChangedEvent);
|
||||
|
||||
// Publish through the Event Bus and mark the saved event as published
|
||||
await _catalogIntegrationEventService.PublishThroughEventBusAsync(priceChangedEvent);
|
||||
using (_catalogContext.Database.BeginTransaction(_eventBus, autoCommit: true))
|
||||
{
|
||||
_eventBus.Publish(nameof(ProductPriceChangedIntegrationEvent), priceChangedEvent);
|
||||
}
|
||||
}
|
||||
else // Just save the updated product because the Product's Price hasn't changed.
|
||||
{
|
||||
|
@ -4,7 +4,6 @@ using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Metadata;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.eShopOnContainers.Services.Catalog.API.Infrastructure;
|
||||
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Events;
|
||||
|
||||
namespace Catalog.API.Infrastructure.Migrations
|
||||
{
|
||||
|
@ -1,43 +0,0 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Metadata;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.eShopOnContainers.BuildingBlocks.IntegrationEventLogEF;
|
||||
|
||||
namespace Catalog.API.Migrations
|
||||
{
|
||||
[DbContext(typeof(IntegrationEventLogContext))]
|
||||
[Migration("20170322145434_IntegrationEventInitial")]
|
||||
partial class IntegrationEventInitial
|
||||
{
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "1.1.1")
|
||||
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
|
||||
|
||||
modelBuilder.Entity("Microsoft.eShopOnContainers.BuildingBlocks.IntegrationEventLogEF.IntegrationEventLogEntry", b =>
|
||||
{
|
||||
b.Property<Guid>("EventId")
|
||||
.ValueGeneratedOnAdd();
|
||||
|
||||
b.Property<string>("Content")
|
||||
.IsRequired();
|
||||
|
||||
b.Property<DateTime>("CreationTime");
|
||||
|
||||
b.Property<string>("EventTypeName")
|
||||
.IsRequired();
|
||||
|
||||
b.Property<int>("State");
|
||||
|
||||
b.Property<int>("TimesSent");
|
||||
|
||||
b.HasKey("EventId");
|
||||
|
||||
b.ToTable("IntegrationEventLog");
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
@ -1,34 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
namespace Catalog.API.Migrations
|
||||
{
|
||||
public partial class IntegrationEventInitial : Migration
|
||||
{
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.CreateTable(
|
||||
name: "IntegrationEventLog",
|
||||
columns: table => new
|
||||
{
|
||||
EventId = table.Column<Guid>(nullable: false),
|
||||
Content = table.Column<string>(nullable: false),
|
||||
CreationTime = table.Column<DateTime>(nullable: false),
|
||||
EventTypeName = table.Column<string>(nullable: false),
|
||||
State = table.Column<int>(nullable: false),
|
||||
TimesSent = table.Column<int>(nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_IntegrationEventLog", x => x.EventId);
|
||||
});
|
||||
}
|
||||
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "IntegrationEventLog");
|
||||
}
|
||||
}
|
||||
}
|
@ -1,42 +0,0 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Metadata;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.eShopOnContainers.BuildingBlocks.IntegrationEventLogEF;
|
||||
|
||||
namespace Catalog.API.Migrations
|
||||
{
|
||||
[DbContext(typeof(IntegrationEventLogContext))]
|
||||
partial class IntegrationEventLogContextModelSnapshot : ModelSnapshot
|
||||
{
|
||||
protected override void BuildModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "1.1.1")
|
||||
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
|
||||
|
||||
modelBuilder.Entity("Microsoft.eShopOnContainers.BuildingBlocks.IntegrationEventLogEF.IntegrationEventLogEntry", b =>
|
||||
{
|
||||
b.Property<Guid>("EventId")
|
||||
.ValueGeneratedOnAdd();
|
||||
|
||||
b.Property<string>("Content")
|
||||
.IsRequired();
|
||||
|
||||
b.Property<DateTime>("CreationTime");
|
||||
|
||||
b.Property<string>("EventTypeName")
|
||||
.IsRequired();
|
||||
|
||||
b.Property<int>("State");
|
||||
|
||||
b.Property<int>("TimesSent");
|
||||
|
||||
b.HasKey("EventId");
|
||||
|
||||
b.ToTable("IntegrationEventLog");
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
@ -1,69 +0,0 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Storage;
|
||||
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Abstractions;
|
||||
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Events;
|
||||
using Microsoft.eShopOnContainers.BuildingBlocks.IntegrationEventLogEF.Services;
|
||||
using Microsoft.eShopOnContainers.BuildingBlocks.IntegrationEventLogEF.Utilities;
|
||||
using Microsoft.eShopOnContainers.Services.Catalog.API;
|
||||
using Microsoft.eShopOnContainers.Services.Catalog.API.Infrastructure;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Serilog.Context;
|
||||
using System;
|
||||
using System.Data.Common;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Catalog.API.IntegrationEvents
|
||||
{
|
||||
public class CatalogIntegrationEventService : ICatalogIntegrationEventService
|
||||
{
|
||||
private readonly Func<DbConnection, IIntegrationEventLogService> _integrationEventLogServiceFactory;
|
||||
private readonly IEventBus _eventBus;
|
||||
private readonly CatalogContext _catalogContext;
|
||||
private readonly IIntegrationEventLogService _eventLogService;
|
||||
private readonly ILogger<CatalogIntegrationEventService> _logger;
|
||||
|
||||
public CatalogIntegrationEventService(
|
||||
ILogger<CatalogIntegrationEventService> logger,
|
||||
IEventBus eventBus,
|
||||
CatalogContext catalogContext,
|
||||
Func<DbConnection, IIntegrationEventLogService> integrationEventLogServiceFactory)
|
||||
{
|
||||
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
_catalogContext = catalogContext ?? throw new ArgumentNullException(nameof(catalogContext));
|
||||
_integrationEventLogServiceFactory = integrationEventLogServiceFactory ?? throw new ArgumentNullException(nameof(integrationEventLogServiceFactory));
|
||||
_eventBus = eventBus ?? throw new ArgumentNullException(nameof(eventBus));
|
||||
_eventLogService = _integrationEventLogServiceFactory(_catalogContext.Database.GetDbConnection());
|
||||
}
|
||||
|
||||
public async Task PublishThroughEventBusAsync(IntegrationEvent evt)
|
||||
{
|
||||
try
|
||||
{
|
||||
_logger.LogInformation("----- Publishing integration event: {IntegrationEventId_published} from {AppName} - ({@IntegrationEvent})", evt.Id, Program.AppName, evt);
|
||||
|
||||
await _eventLogService.MarkEventAsInProgressAsync(evt.Id);
|
||||
_eventBus.Publish(evt);
|
||||
await _eventLogService.MarkEventAsPublishedAsync(evt.Id);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "ERROR Publishing integration event: {IntegrationEventId} from {AppName} - ({@IntegrationEvent})", evt.Id, Program.AppName, evt);
|
||||
await _eventLogService.MarkEventAsFailedAsync(evt.Id);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task SaveEventAndCatalogContextChangesAsync(IntegrationEvent evt)
|
||||
{
|
||||
_logger.LogInformation("----- CatalogIntegrationEventService - Saving changes and integrationEvent: {IntegrationEventId}", evt.Id);
|
||||
|
||||
//Use of an EF Core resiliency strategy when using multiple DbContexts within an explicit BeginTransaction():
|
||||
//See: https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-resiliency
|
||||
await ResilientTransaction.New(_catalogContext).ExecuteAsync(async () =>
|
||||
{
|
||||
// Achieving atomicity between original catalog database operation and the IntegrationEventLog thanks to a local transaction
|
||||
await _catalogContext.SaveChangesAsync();
|
||||
await _eventLogService.SaveEventAsync(evt, _catalogContext.Database.CurrentTransaction.GetDbTransaction());
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
@ -1,39 +1,36 @@
|
||||
namespace Microsoft.eShopOnContainers.Services.Catalog.API.IntegrationEvents.EventHandling
|
||||
using DotNetCore.CAP;
|
||||
|
||||
namespace Microsoft.eShopOnContainers.Services.Catalog.API.IntegrationEvents.EventHandling
|
||||
{
|
||||
using BuildingBlocks.EventBus.Abstractions;
|
||||
using System.Threading.Tasks;
|
||||
using BuildingBlocks.EventBus.Events;
|
||||
using Infrastructure;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using global::Catalog.API.IntegrationEvents;
|
||||
using IntegrationEvents.Events;
|
||||
using Events;
|
||||
using Serilog.Context;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Extensions.Logging;
|
||||
|
||||
public class OrderStatusChangedToAwaitingValidationIntegrationEventHandler :
|
||||
IIntegrationEventHandler<OrderStatusChangedToAwaitingValidationIntegrationEvent>
|
||||
public class OrderStatusChangedToAwaitingValidationIntegrationEventHandler : ICapSubscribe
|
||||
{
|
||||
private readonly CatalogContext _catalogContext;
|
||||
private readonly ICatalogIntegrationEventService _catalogIntegrationEventService;
|
||||
private readonly ICapPublisher _eventBus;
|
||||
private readonly ILogger<OrderStatusChangedToAwaitingValidationIntegrationEventHandler> _logger;
|
||||
|
||||
public OrderStatusChangedToAwaitingValidationIntegrationEventHandler(
|
||||
CatalogContext catalogContext,
|
||||
ICatalogIntegrationEventService catalogIntegrationEventService,
|
||||
ICapPublisher eventBus,
|
||||
ILogger<OrderStatusChangedToAwaitingValidationIntegrationEventHandler> logger)
|
||||
{
|
||||
_catalogContext = catalogContext;
|
||||
_catalogIntegrationEventService = catalogIntegrationEventService;
|
||||
_eventBus = eventBus;
|
||||
_logger = logger ?? throw new System.ArgumentNullException(nameof(logger));
|
||||
}
|
||||
|
||||
//TODO: [CapSubscribe(nameof(OrderStatusChangedToAwaitingValidationIntegrationEvent))]
|
||||
public async Task Handle(OrderStatusChangedToAwaitingValidationIntegrationEvent @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);
|
||||
|
||||
var confirmedOrderStockItems = new List<ConfirmedOrderStockItem>();
|
||||
|
||||
foreach (var orderStockItem in @event.OrderStockItems)
|
||||
@ -43,15 +40,18 @@
|
||||
var confirmedOrderStockItem = new ConfirmedOrderStockItem(catalogItem.Id, hasStock);
|
||||
|
||||
confirmedOrderStockItems.Add(confirmedOrderStockItem);
|
||||
}
|
||||
|
||||
if (confirmedOrderStockItems.Any(c => !c.HasStock))
|
||||
{
|
||||
await _eventBus.PublishAsync(nameof(OrderStockRejectedIntegrationEvent),
|
||||
new OrderStockRejectedIntegrationEvent(@event.OrderId, confirmedOrderStockItems));
|
||||
}
|
||||
|
||||
var confirmedIntegrationEvent = confirmedOrderStockItems.Any(c => !c.HasStock)
|
||||
? (IntegrationEvent)new OrderStockRejectedIntegrationEvent(@event.OrderId, confirmedOrderStockItems)
|
||||
: new OrderStockConfirmedIntegrationEvent(@event.OrderId);
|
||||
|
||||
await _catalogIntegrationEventService.SaveEventAndCatalogContextChangesAsync(confirmedIntegrationEvent);
|
||||
await _catalogIntegrationEventService.PublishThroughEventBusAsync(confirmedIntegrationEvent);
|
||||
|
||||
else
|
||||
{
|
||||
await _eventBus.PublishAsync(nameof(OrderStockConfirmedIntegrationEvent),
|
||||
new OrderStockConfirmedIntegrationEvent(@event.OrderId));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,14 +1,15 @@
|
||||
namespace Microsoft.eShopOnContainers.Services.Catalog.API.IntegrationEvents.EventHandling
|
||||
using DotNetCore.CAP;
|
||||
|
||||
namespace Microsoft.eShopOnContainers.Services.Catalog.API.IntegrationEvents.EventHandling
|
||||
{
|
||||
using BuildingBlocks.EventBus.Abstractions;
|
||||
using System.Threading.Tasks;
|
||||
using Infrastructure;
|
||||
using Microsoft.eShopOnContainers.Services.Catalog.API.IntegrationEvents.Events;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Events;
|
||||
using Extensions.Logging;
|
||||
using Serilog.Context;
|
||||
|
||||
public class OrderStatusChangedToPaidIntegrationEventHandler :
|
||||
IIntegrationEventHandler<OrderStatusChangedToPaidIntegrationEvent>
|
||||
//OrderStatusChangedToPaidIntegrationEvent
|
||||
public class OrderStatusChangedToPaidIntegrationEventHandler : ICapSubscribe
|
||||
{
|
||||
private readonly CatalogContext _catalogContext;
|
||||
private readonly ILogger<OrderStatusChangedToPaidIntegrationEventHandler> _logger;
|
||||
@ -21,11 +22,12 @@
|
||||
_logger = logger ?? throw new System.ArgumentNullException(nameof(logger));
|
||||
}
|
||||
|
||||
//TODO: [CapSubscribe(nameof(OrderStatusChangedToPaidIntegrationEvent))]
|
||||
public async Task Handle(OrderStatusChangedToPaidIntegrationEvent @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);
|
||||
|
||||
//we're not blocking stock/inventory
|
||||
foreach (var orderStockItem in @event.OrderStockItems)
|
||||
@ -36,7 +38,6 @@
|
||||
}
|
||||
|
||||
await _catalogContext.SaveChangesAsync();
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,9 +1,8 @@
|
||||
namespace Microsoft.eShopOnContainers.Services.Catalog.API.IntegrationEvents.Events
|
||||
{
|
||||
using BuildingBlocks.EventBus.Events;
|
||||
using System.Collections.Generic;
|
||||
|
||||
public class OrderStatusChangedToAwaitingValidationIntegrationEvent : IntegrationEvent
|
||||
public class OrderStatusChangedToAwaitingValidationIntegrationEvent
|
||||
{
|
||||
public int OrderId { get; }
|
||||
public IEnumerable<OrderStockItem> OrderStockItems { get; }
|
||||
|
@ -1,9 +1,8 @@
|
||||
namespace Microsoft.eShopOnContainers.Services.Catalog.API.IntegrationEvents.Events
|
||||
{
|
||||
using System.Collections.Generic;
|
||||
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Events;
|
||||
|
||||
public class OrderStatusChangedToPaidIntegrationEvent : IntegrationEvent
|
||||
public class OrderStatusChangedToPaidIntegrationEvent
|
||||
{
|
||||
public int OrderId { get; }
|
||||
public IEnumerable<OrderStockItem> OrderStockItems { get; }
|
||||
|
@ -1,8 +1,6 @@
|
||||
namespace Microsoft.eShopOnContainers.Services.Catalog.API.IntegrationEvents.Events
|
||||
{
|
||||
using BuildingBlocks.EventBus.Events;
|
||||
|
||||
public class OrderStockConfirmedIntegrationEvent : IntegrationEvent
|
||||
public class OrderStockConfirmedIntegrationEvent
|
||||
{
|
||||
public int OrderId { get; }
|
||||
|
||||
|
@ -1,9 +1,8 @@
|
||||
namespace Microsoft.eShopOnContainers.Services.Catalog.API.IntegrationEvents.Events
|
||||
{
|
||||
using BuildingBlocks.EventBus.Events;
|
||||
using System.Collections.Generic;
|
||||
|
||||
public class OrderStockRejectedIntegrationEvent : IntegrationEvent
|
||||
public class OrderStockRejectedIntegrationEvent
|
||||
{
|
||||
public int OrderId { get; }
|
||||
|
||||
|
@ -1,11 +1,9 @@
|
||||
namespace Microsoft.eShopOnContainers.Services.Catalog.API.IntegrationEvents.Events
|
||||
{
|
||||
using BuildingBlocks.EventBus.Events;
|
||||
|
||||
// Integration Events notes:
|
||||
// An Event is “something that has happened in the past”, therefore its name has to be
|
||||
// An Integration Event is an event that can cause side effects to other microsrvices, Bounded-Contexts or external systems.
|
||||
public class ProductPriceChangedIntegrationEvent : IntegrationEvent
|
||||
public class ProductPriceChangedIntegrationEvent
|
||||
{
|
||||
public int ProductId { get; private set; }
|
||||
|
||||
|
@ -1,11 +0,0 @@
|
||||
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Events;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Catalog.API.IntegrationEvents
|
||||
{
|
||||
public interface ICatalogIntegrationEventService
|
||||
{
|
||||
Task SaveEventAndCatalogContextChangesAsync(IntegrationEvent evt);
|
||||
Task PublishThroughEventBusAsync(IntegrationEvent evt);
|
||||
}
|
||||
}
|
@ -1,6 +1,5 @@
|
||||
using Microsoft.AspNetCore;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.eShopOnContainers.BuildingBlocks.IntegrationEventLogEF;
|
||||
using Microsoft.eShopOnContainers.Services.Catalog.API.Infrastructure;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
@ -38,8 +37,7 @@ namespace Microsoft.eShopOnContainers.Services.Catalog.API
|
||||
new CatalogContextSeed()
|
||||
.SeedAsync(context, env, settings, logger)
|
||||
.Wait();
|
||||
})
|
||||
.MigrateDbContext<IntegrationEventLogContext>((_, __) => { });
|
||||
});
|
||||
|
||||
Log.Information("Starting web host ({ApplicationContext})...", AppName);
|
||||
host.Run();
|
||||
|
@ -1,32 +1,20 @@
|
||||
using Autofac;
|
||||
using Autofac.Extensions.DependencyInjection;
|
||||
using global::Catalog.API.Infrastructure.Filters;
|
||||
using global::Catalog.API.IntegrationEvents;
|
||||
using Microsoft.ApplicationInsights.Extensibility;
|
||||
using Microsoft.ApplicationInsights.ServiceFabric;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Azure.ServiceBus;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Diagnostics;
|
||||
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus;
|
||||
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Abstractions;
|
||||
using Microsoft.eShopOnContainers.BuildingBlocks.EventBusRabbitMQ;
|
||||
using Microsoft.eShopOnContainers.BuildingBlocks.EventBusServiceBus;
|
||||
using Microsoft.eShopOnContainers.BuildingBlocks.IntegrationEventLogEF;
|
||||
using Microsoft.eShopOnContainers.BuildingBlocks.IntegrationEventLogEF.Services;
|
||||
using Microsoft.eShopOnContainers.Services.Catalog.API.Infrastructure;
|
||||
using Microsoft.eShopOnContainers.Services.Catalog.API.IntegrationEvents.EventHandling;
|
||||
using Microsoft.eShopOnContainers.Services.Catalog.API.IntegrationEvents.Events;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using RabbitMQ.Client;
|
||||
using System;
|
||||
using System.Data.Common;
|
||||
using System.Reflection;
|
||||
using HealthChecks.UI.Client;
|
||||
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
|
||||
@ -49,7 +37,7 @@ namespace Microsoft.eShopOnContainers.Services.Catalog.API
|
||||
.AddCustomMVC(Configuration)
|
||||
.AddCustomDbContext(Configuration)
|
||||
.AddCustomOptions(Configuration)
|
||||
.AddIntegrationServices(Configuration)
|
||||
.AddIntegrationServices()
|
||||
.AddEventBus(Configuration)
|
||||
.AddSwagger()
|
||||
.AddCustomHealthCheck(Configuration);
|
||||
@ -95,15 +83,6 @@ namespace Microsoft.eShopOnContainers.Services.Catalog.API
|
||||
{
|
||||
c.SwaggerEndpoint($"{ (!string.IsNullOrEmpty(pathBase) ? pathBase : string.Empty) }/swagger/v1/swagger.json", "Catalog.API V1");
|
||||
});
|
||||
|
||||
ConfigureEventBus(app);
|
||||
}
|
||||
|
||||
protected virtual void ConfigureEventBus(IApplicationBuilder app)
|
||||
{
|
||||
var eventBus = app.ApplicationServices.GetRequiredService<IEventBus>();
|
||||
eventBus.Subscribe<OrderStatusChangedToAwaitingValidationIntegrationEvent, OrderStatusChangedToAwaitingValidationIntegrationEventHandler>();
|
||||
eventBus.Subscribe<OrderStatusChangedToPaidIntegrationEvent, OrderStatusChangedToPaidIntegrationEventHandler>();
|
||||
}
|
||||
}
|
||||
|
||||
@ -130,7 +109,7 @@ namespace Microsoft.eShopOnContainers.Services.Catalog.API
|
||||
}
|
||||
|
||||
public static IServiceCollection AddCustomMVC(this IServiceCollection services, IConfiguration configuration)
|
||||
{
|
||||
{
|
||||
services.AddMvc(options =>
|
||||
{
|
||||
options.Filters.Add(typeof(HttpGlobalExceptionFilter));
|
||||
@ -166,7 +145,7 @@ namespace Microsoft.eShopOnContainers.Services.Catalog.API
|
||||
tags: new string[] { "catalogdb" });
|
||||
|
||||
if (!string.IsNullOrEmpty(accountName) && !string.IsNullOrEmpty(accountKey))
|
||||
{
|
||||
{
|
||||
hcBuilder
|
||||
.AddAzureBlobStorage(
|
||||
$"DefaultEndpointsProtocol=https;AccountName={accountName};AccountKey={accountKey};EndpointSuffix=core.windows.net",
|
||||
@ -213,17 +192,6 @@ namespace Microsoft.eShopOnContainers.Services.Catalog.API
|
||||
//Check Client vs. Server evaluation: https://docs.microsoft.com/en-us/ef/core/querying/client-eval
|
||||
});
|
||||
|
||||
services.AddDbContext<IntegrationEventLogContext>(options =>
|
||||
{
|
||||
options.UseSqlServer(configuration["ConnectionString"],
|
||||
sqlServerOptionsAction: sqlOptions =>
|
||||
{
|
||||
sqlOptions.MigrationsAssembly(typeof(Startup).GetTypeInfo().Assembly.GetName().Name);
|
||||
//Configuring Connection Resiliency: https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-resiliency
|
||||
sqlOptions.EnableRetryOnFailure(maxRetryCount: 10, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null);
|
||||
});
|
||||
});
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
@ -269,100 +237,51 @@ namespace Microsoft.eShopOnContainers.Services.Catalog.API
|
||||
|
||||
}
|
||||
|
||||
public static IServiceCollection AddIntegrationServices(this IServiceCollection services, IConfiguration configuration)
|
||||
public static IServiceCollection AddIntegrationServices(this IServiceCollection services)
|
||||
{
|
||||
services.AddTransient<Func<DbConnection, IIntegrationEventLogService>>(
|
||||
sp => (DbConnection c) => new IntegrationEventLogService(c));
|
||||
|
||||
services.AddTransient<ICatalogIntegrationEventService, CatalogIntegrationEventService>();
|
||||
|
||||
if (configuration.GetValue<bool>("AzureServiceBusEnabled"))
|
||||
{
|
||||
services.AddSingleton<IServiceBusPersisterConnection>(sp =>
|
||||
{
|
||||
var settings = sp.GetRequiredService<IOptions<CatalogSettings>>().Value;
|
||||
var logger = sp.GetRequiredService<ILogger<DefaultServiceBusPersisterConnection>>();
|
||||
|
||||
var serviceBusConnection = new ServiceBusConnectionStringBuilder(settings.EventBusConnection);
|
||||
|
||||
return new DefaultServiceBusPersisterConnection(serviceBusConnection, logger);
|
||||
});
|
||||
}
|
||||
else
|
||||
{
|
||||
services.AddSingleton<IRabbitMQPersistentConnection>(sp =>
|
||||
{
|
||||
var settings = sp.GetRequiredService<IOptions<CatalogSettings>>().Value;
|
||||
var logger = sp.GetRequiredService<ILogger<DefaultRabbitMQPersistentConnection>>();
|
||||
|
||||
var factory = new ConnectionFactory()
|
||||
{
|
||||
HostName = configuration["EventBusConnection"]
|
||||
};
|
||||
|
||||
if (!string.IsNullOrEmpty(configuration["EventBusUserName"]))
|
||||
{
|
||||
factory.UserName = configuration["EventBusUserName"];
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(configuration["EventBusPassword"]))
|
||||
{
|
||||
factory.Password = configuration["EventBusPassword"];
|
||||
}
|
||||
|
||||
var retryCount = 5;
|
||||
if (!string.IsNullOrEmpty(configuration["EventBusRetryCount"]))
|
||||
{
|
||||
retryCount = int.Parse(configuration["EventBusRetryCount"]);
|
||||
}
|
||||
|
||||
return new DefaultRabbitMQPersistentConnection(factory, logger, retryCount);
|
||||
});
|
||||
}
|
||||
//Handlers
|
||||
services.AddTransient<OrderStatusChangedToAwaitingValidationIntegrationEventHandler>(); // OrderStatusChangedToAwaitingValidationIntegrationEvent
|
||||
services.AddTransient<OrderStatusChangedToPaidIntegrationEventHandler>(); // OrderStatusChangedToPaidIntegrationEvent
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
public static IServiceCollection AddEventBus(this IServiceCollection services, IConfiguration configuration)
|
||||
{
|
||||
var subscriptionClientName = configuration["SubscriptionClientName"];
|
||||
|
||||
if (configuration.GetValue<bool>("AzureServiceBusEnabled"))
|
||||
services.AddCap(options =>
|
||||
{
|
||||
services.AddSingleton<IEventBus, EventBusServiceBus>(sp =>
|
||||
options.UseSqlServer(configuration["ConnectionString"]);
|
||||
|
||||
if (configuration.GetValue<bool>("AzureServiceBusEnabled"))
|
||||
{
|
||||
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 =>
|
||||
options.UseAzureServiceBus(configuration["EventBusConnection"]);
|
||||
}
|
||||
else
|
||||
{
|
||||
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"]))
|
||||
options.UseRabbitMQ(conf =>
|
||||
{
|
||||
retryCount = int.Parse(configuration["EventBusRetryCount"]);
|
||||
}
|
||||
conf.HostName = configuration["EventBusConnection"];
|
||||
if (!string.IsNullOrEmpty(configuration["EventBusUserName"]))
|
||||
{
|
||||
conf.UserName = configuration["EventBusUserName"];
|
||||
}
|
||||
if (!string.IsNullOrEmpty(configuration["EventBusPassword"]))
|
||||
{
|
||||
conf.Password = configuration["EventBusPassword"];
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return new EventBusRabbitMQ(rabbitMQPersistentConnection, logger, iLifetimeScope, eventBusSubcriptionsManager, subscriptionClientName, retryCount);
|
||||
});
|
||||
}
|
||||
if (!string.IsNullOrEmpty(configuration["EventBusRetryCount"]))
|
||||
{
|
||||
options.FailedRetryCount = int.Parse(configuration["EventBusRetryCount"]);
|
||||
}
|
||||
|
||||
services.AddSingleton<IEventBusSubscriptionsManager, InMemoryEventBusSubscriptionsManager>();
|
||||
services.AddTransient<OrderStatusChangedToAwaitingValidationIntegrationEventHandler>();
|
||||
services.AddTransient<OrderStatusChangedToPaidIntegrationEventHandler>();
|
||||
if (!string.IsNullOrEmpty(configuration["SubscriptionClientName"]))
|
||||
{
|
||||
options.DefaultGroup = configuration["SubscriptionClientName"];
|
||||
}
|
||||
});
|
||||
|
||||
return services;
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user