Communication is the key. Especially, when there is a high transaction distributed application with thousands of loosely coupled entities involved. In that case, there is a dire need for scalable and flexible communication between different modules to keep your application running smoothly without stale information.
Since newly emerging applications are shifting to the microservices-based architecture, here are some fundamental questions you need to consider while designing the backing communication architecture of relevant applications.
- Is it scalable?
- Is it reliable?
- Is it storage efficient?
NCache is an in-memory distributed cache that has been widely adopted to enhance the performance of microservices-based .NET/ .NET Core applications. NCache now provides a Publisher-Subscriber (Pub/Sub) feature to enable an event-driven messaging paradigm for these applications.
NCache Details NCache Pub/Sub NCache Docs
Introducing NCache Pub/Sub
NCache provides an in-memory Pub/Sub messaging to enable real-time information sharing in .NET web applications. The Pub/Sub model naturally decouples publishers and subscribers by providing a channel where messages are published and subscribed by the interested users. Now when NCache acts as a messaging bus, the Pub/Sub model benefits from the underlying NCache distributed architecture and numerous handy features. We will see that how combining NCache and Pub/Sub can address the above challenges and eventually help your applications communicate better.
You can see the core components of NCache Pub/Sub to understand the basics of this feature. Without further ado, let’s first see how to get things done to utilize the Pub/Sub messaging.
How to Use NCache Pub/Sub Messaging
Assume that you have an e-commerce application where you need to be notified of every new product added to the store. Since it can be achieved using NCache Pub/Sub, you first need to create a cache. It is recommended to have a dedicated cache for Pub/Sub. Next, we discuss the step-by-step process of creating a topic for getting notifications relevant to new products, publishing messages, and subscribing for messages.
NCache Details NCache Pub/Sub NCache Docs
Create a Topic
NCache provides an ITopic
interface to create a topic with a unique name. Here is how your publisher application can create a topic with the name newProducts using the method CreateTopic
.
1 2 3 4 5 6 |
// Pre-condition: Cache is already connected // Specify the topic name string topicName = “newProducts” // Create topic ITopic topic = cache.MessagingService.CreateTopic(topicName); |
If the topic already exists, an instance of the topic is returned as ITopic
.
It may happen that, certain events are more important and need to be communicated as soon as they occur. For instance, getting notified about finished goods/products on sale can be most important being a seller/buyer. In that case, you can set topic priority to high while creating the topic, and receive the relevant notifications without any wait.
Publish Messages
Once a topic is created, the publisher application can publish relevant messages to that topic using Publish
method. For that, you first get an instance of the topic by providing the name of the topic. The following code shows that how you can publish a message relevant to a new product to an already existing topic newProducts.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// Pre-condition: Cache is already connected // Topic “newProducts” already created string topicName = “newProducts” // Get the topic ITopic productTopic = cache.MessagingService.GetTopic(topicName); // Create the object to be sent in message Product product = FetchProductFromDB(10248); // Create the new message with the object order var productMessage = new Message(product); // Publish the order with delivery option set as all orderTopic.Publish(productMessage, DeliveryOption.All, true); |
Being a publisher, you may need to broadcast certain messages or deliver to any based on the scenario of the application. For instance, if the price of a product is updated, all the subscribers should be notified. However, this may not be the case always. Keeping that in view, the delivery mode can be specified while publishing messages. The following two message delivery options are provided by NCache Pub/Sub.
- All (default): Delivers the message to all the registered subscribers.
- Any: Delivers the message to any of the registered subscribers.
See delivery options for more details.
Furthermore, to efficiently manage the storage space of your Pub/Sub cache, you can also set expirations for messages.
Subscribe to a Topic
After a message has been published against a topic, your subscriber application creates a subscription against that topic to receive messages using the CreateSubscription
method. The code below shows how a subscriber application can create a subscription for the topic newProducts with MessageReceived
callback.
1 2 3 4 5 6 7 8 9 10 |
// Pre-condition: Cache is already connected // Topic “newProducts” already created string topicName = “newProducts” // Get the topic ITopic productTopic = cache.MessagingService.GetTopic(topicName); // Create and register subscribers for topic newProducts // MessageReceived callback is specified ITopicSubscription orderSubscriber = orderTopic.CreateSubscription(MessageReceived); |
Assume that, the subscriber application needs to update product prices on receiving sale notifications. Then, the intended price update operation can be performed in the MessageReceived
callback.
A subscription created in the above example is non-durable and the subscriptions are non-durable by default. Besides, you can also create a durable subscription using the NCache IDurableTopicSubscription
interface. In case of a durable subscription, NCache retains the subscription of a subscriber on connection loss. It means that the messages published on a topic are assigned to the subscription even if the subscriber is offline. Hence, the subscriber can receive these messages on reconnecting.
And what’s more, you can subscribe to single/multiple topics falling under the provided pattern using the pattern-based method of subscription where NCache supports multiple wildcards.
Register Notifications
Being a publisher, you may need to know the status of messages and the availability of topics. Let’s see what kind of notifications your publisher applications can register for while using NCache Pub/Sub messaging.
MessageDeliveryFailure:
to get notified if the message has failed to deliver because of any issue.OnTopicDeleted:
to get notified when a topic is deleted.
Here is how simply the publisher can register for these two types of notifications.
1 2 3 4 5 6 7 |
// You have an instance productTopic of existing topic // Register message delivery failure productTopic.MessageDeliveryFailure += OnFailureMessageReceived; //Register topic deletion notification productTopic.OnTopicDeleted = TopicDeleted; |
Why NCache Pub/Sub for Distributed Messaging?
To this point, we are familiar with the NCache Pub/Sub feature. Now, what benefits does Ncache Pub/Sub offers to handle the questions raised initially?
- NCache provides linear scalability due to which your application can handle the increasing number of subscription requests seamlessly.
- NCache ensures the high availability of NCache that accommodates subscribers’ connectivity in dynamic environments.
- NCache allows expiration and evictions on items residing in the cache to intelligently manage the storage space.
Hence, the above features together with loose coupling and async messaging mode of Pub/Sub make NCache Pub/Sub feature highly promising for distributed messaging in your future .Net applications.