Date:

Share:

Learn How To Publish and Subscribe to Events

Related Articles

This article is sponsored by AWS and is part of my AWS series.

NServiceBus is a messaging framework that makes it easy to send, process, and publish messages across various on-premises and cloud-based queuing technologies.

In a previous blog post, we learned how to quickly get started with NServiceBus on AWS SQS. We learned how to install and configure NServiceBus, configure the receiver and sender to listen for messages in Amazon SQS Transport, and communicate between the two using commands.

In this blog post, let’s explore how to publish events using NServiceBus.

We will learn how to do

  • Publish events with NServiceBus
  • Register for events with NServiceBus
  • How it works under the hood

Publish events with NServiceBus

An event is a different type of message that is posted to multiple receivers, as opposed to a command sent to a single receiver.

Events indicate an action that has occurred.

To mark a message as an event in NServiceBus, it must implement the IEvent interface.

Continuing with the same code example from our blog for getting started, we can upload a UserCreatedEvent within our CreateUserCommandHandler Every time a user is created successfully.

public class UserCreatedEvent : IEvent
{
    public Guid UserId { get; set; }
    public DateTimeOffset CreatedDateTime { get; set; }

    public UserCreatedEvent(Guid userId, DateTimeOffset createdDateTime)
    {
        UserId = userId;
        CreatedDateTime = createdDateTime;
    }
}

A generated user indicates an action that has occurred and can be used to notify other applications that are interested in it.

The context for the NServiceBus message handler IMessageHandlerContext there is Publish A method of publishing events.

Let’s update you CreateUserCommandHandler To post the new event after the job is done to create a new user.

public async Task Handle(
    CreateUserCommand message, IMessageHandlerContext context)
{
    log.Info($"Processed message for user with Id {message.Id}, and {message.Name}");

    // Create the user
    // Save To database/persistent store

    await context
      .Publish(new UserCreatedEvent(message.Id, DateTimeOffset.UtcNow);
}

Register for events with NServiceBus

Other apps interested in published events can subscribe to them.

In NServiceBus, this is done by creating a class and implementing the IHandleMessages interface.

Below is an example in payroll-service Application, which is interested in UserCreatedEvent.

internal class UserCreatedHandler : IHandleMessages<UserCreatedEvent>
{
    static ILog log = LogManager.GetLogger<UserCreatedHandler>();

    public Task Handle(UserCreatedEvent message, IMessageHandlerContext context)
    {
        log.Info($"Payroll Service User created handler for User Id {message.UserId}");

        // handle appropriate for payroll service

        return Task.CompletedTask;
    }
}

Each time a user is created, the payroll application needs to set up new accounts for the user. You can handle this in the handler associated with the payroll application code.

Configuring NServiceBus Event Manager in AWS SQS Transport

Activation code for payroll-service Very similar to how we configure receiver endpoints in Amazon SQS Transport.

It defines a new endpoint by specifying EndpointConfiguration and the definition of transport. The endpoint is called “payroll serviceand uses Amazon SQS as its underlying transport.

Although the transport is called by name SqsTransport It also uses Amazon SNS under the hood, which we’ll see later.

using NServiceBus;

Console.WriteLine("Hello, World!");

var endpointConfiguration = new EndpointConfiguration("payroll-service");
var transport = endpointConfiguration.UseTransport<SqsTransport>();
transport.S3(bucketForLargeMessages: "user-service-large-messages", keyPrefix: "user");
endpointConfiguration.EnableInstallers();

var endointInstance = await Endpoint.Start(endpointConfiguration);

Console.WriteLine("Press any key to stop");
Console.ReadKey();

await endointInstance.Stop();

If other applications are interested in the same events, additional handlers for the same event can be added in those applications as well.

For example, the TaskForce/HR department may also be interested in UserCreatedEvent. Add a new handler in the appropriate application code as needed.

anytime UserCreatedEvent It grows, these handlers are called independent of each other. This allows decoupling of the resulting user logic and the associated side effects that must happen.

NServiceBus Events on AWS – Under The Hood

NServiceBus uses a combination of Amazon SNS and SQS to deliver events to multiple subscribers.

Amazon Simple Notification Service (SNS) is an advertising subscription service managed by AWS. It enables asynchronous communication between publishers and subscribers via messages.

Amazon SNS for .NET Developer: Getting started is quick and easy

Learn how to get started with Amazon SNS and use it from a .NET application. We will learn about topics, sending messages to topics and using subscriptions to receive messages. We will also learn about filters, how to use them and error handling with SNS.

An SNS topic is automatically created for the event by NServiceBus and adds a subscriber to the SQS queue that the service is listening to.

Whenever an event is published to an SNS topic, it sends a copy to the SQS queue.

NServiceBus uses a combination of Amazon SNS and SQS to deliver events to multiple subscribers. An SNS topic is automatically created for the event, and adds a subscription to the SQS queue that the service listens to.

In this case, we have an SNS topic created with the name user_messages-UserCreatedEvent. It also creates a queue for task-force-service And an additional subscription to the SNS queue.

When UserCreatedEvent The message is forwarded to task-force-service SQS Queue, NServiceBus delivers the message to the event handler for that application/endpoint.

When you add more subscribers to the same event, it adds more subscribers to the SNS and forwards a copy of the event message to all subscribers.

Multiple subscribers are created on an SNS topic to deliver a copy of the same event message to different subscribers.

Even if the individual applications handling the event messages are not running, a copy of the message is sent to the queue. When the application runs back, it can process the events and perform the associated handler functions.

If you want to learn more about application decoupling using SNS -> SQS, you can check out the blog post below, which I cover in full detail.

SNS→Lambda or SNS→SQS→Lambda

Should you process messages directly from SNS to Lambda or through an SQS queue? Learn the disadvantages of directly processing messages from SNS and how you can solve them by introducing an SQS queue in the middle.

Large event notification sizes

It is generally recommended to keep the event data short. Including properties that don’t change often, like IDs, date and time, URLs, etc., helps convey relevant information while keeping the size small.

However, in cases where you need to transfer larger sizes, we can use Amazon S3 storage to download the actual message and pass the URL of the S3 object in the event data.

In the previous post, we saw how to set this up when dealing with large message sizes with NServiceBus and SQS Transport.

Full source code sample Available here.

Source

Popular Articles