Last active
March 14, 2018 12:39
-
-
Save ramonsmits/62641b7ed7e5fe5da8b901d707a930e2 to your computer and use it in GitHub Desktop.
Business metric collector and calculation sample using NServiceBus events and sagas
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.Threading.Tasks; | |
| using NServiceBus; | |
| class ShippingSpeedMetricCollector | |
| : Saga<ShippingSpeedData> | |
| , IAmStartedByMessages<OrderCreated> | |
| , IHandleMessages<OrderCancelled> | |
| , IHandleMessages<OrderShipped> | |
| { | |
| public Task Handle(OrderCreated message, IMessageHandlerContext context) | |
| { | |
| var createdAt = DateTimeExtensions.ToUtcDateTime(context.MessageHeaders[Headers.TimeSent]); | |
| Data.CreatedAt = createdAt; | |
| return Task.CompletedTask; | |
| } | |
| public Task Handle(OrderCancelled message, IMessageHandlerContext context) | |
| { | |
| MarkAsComplete(); | |
| return Task.CompletedTask; | |
| } | |
| public Task Handle(OrderShipped message, IMessageHandlerContext context) | |
| { | |
| var shippedAt = DateTimeExtensions.ToUtcDateTime(context.MessageHeaders[Headers.TimeSent]); | |
| var duration = Data.CreatedAt - shippedAt; | |
| MarkAsComplete(); | |
| return context.Send(new UpdateShippedMetric { OrderId = message.OrderId, Duration = duration }); | |
| } | |
| protected override void ConfigureHowToFindSaga(SagaPropertyMapper<ShippingSpeedData> mapper) | |
| { | |
| mapper.ConfigureMapping<OrderCreated>(m => m.OrderId).ToSaga(s => s.OrderId); | |
| mapper.ConfigureMapping<OrderCancelled>(m => m.OrderId).ToSaga(s => s.OrderId); | |
| mapper.ConfigureMapping<OrderShipped>(m => m.OrderId).ToSaga(s => s.OrderId); | |
| } | |
| } | |
| class ShippingSpeedData : ContainSagaData | |
| { | |
| public string OrderId { get; set; } | |
| public DateTime CreatedAt { get; set; } | |
| } | |
| class SendUpdateShippedMetricToInfluxDB : IHandleMessages<UpdateShippedMetric> | |
| { | |
| public Task Handle(UpdateShippedMetric message, IMessageHandlerContext context) | |
| { | |
| // Connect to InfluxDB and add data | |
| return Task.CompletedTask; | |
| } | |
| } | |
| class UpdateShippedMetric : ICommand | |
| { | |
| public string OrderId { get; set; } | |
| public TimeSpan Duration { get; set; } | |
| } | |
| class OrderShipped : IEvent | |
| { | |
| public string OrderId { get; set; } | |
| } | |
| class OrderCreated : IEvent | |
| { | |
| public string OrderId { get; set; } | |
| } | |
| class OrderCancelled : IEvent | |
| { | |
| public string OrderId { get; set; } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment