Pub/Sub Messaging, Continuous Query, and Events

Many server applications today need to coordinate work with other applications to share messages and data asynchronously and often, this is done in a high transaction environment. For high transaction environments, NCache is an ideal candidate for these asynchronous event driven communications.

NCache provides a rich set of features to cater to the needs of these applications including Pub/Sub Messaging, Continuous Queries, Item Level Events, and Cache Level Events. Each is described below.

Pub/Sub Messaging, Continuous Query, and Events

Pub/Sub Messaging

Pub/Sub Messaging is a messaging medium, provided by NCache for the .NET applications. It is responsible for exchanging messages between multiple applications where the Publisher sends the messages without knowing who the subscriber(s) is. The channel used for the exchange of messages is called Topic and the subscriber subscribes to their topic of interest for receiving the relevant messages. NCache provides multiple types of subscriptions between the subscribers and publishers.

You can easily use NCache Pub/Sub messaging for distributed applications once you understand the components of Pub/Sub messaging and their working.

Pub/Sub Messaging with NCache

Below is a source code example on how a Publisher publishes a message to a topic and then a subscriber subscribes to the topic.

ITopic topic = _cache.MessagingService.CreateTopic(topicName)

// Creating new message containing a “payload” 
var message = new Message(payload);

// Set the expiration TimeSpan of the message
message.ExpirationTime = TimeSpan.FromSeconds(5000);

// Publishing the above created message.
topic.Publish(message, DeliveryOption.All, true);

// Get the already created topic to subscribe to it
ITopic orderTopic = cache.MessagingService.GetTopic(topic);

// Create and register subscribers for the topic created
// MessageRecieved callback is registered
orderTopic.CreateSubscription(MessageReceived);

Continuous Query (CQ)

Continuous query is a feature provided by NCache for monitoring data changes in the cache based on SQL criteria. SQL queries are performed on the data and NCache then monitors the desired data-set for any changes. And, events are fired on any of the following changes occurring in the cache.

  • Add: Addition of an item in the cache which fulfills the query. Returns either the entire object or its key and meta-data.
  • Update: Updating the item in the cache which is a part of the result set. Returns either the entire object or its key and meta-data.
  • Remove: Removing an item from the cache which is a part of the result set or updating any item in the cache in such a way that it no longer fulfills the query criteria. Returns either the entire object or its key and meta-data.

Here is how you can create a Continuous Query with specific criteria and register against the server.

// Query for required operation
string query = "SELECT $VALUE$ FROM FQN.Customer WHERE Country = ?";

var queryCommand = new QueryCommand(query);
queryCommand.Parameters.Add("Country", "USA");

// Create Continuous Query
var cQuery = new ContinuousQuery(queryCommand);

// Register to be notified when a qualified item is added to the cache
cQuery.RegisterNotification(new QueryDataNotificationCallback(QueryItemCallBack), EventType.ItemAdded, EventDataFilter.None);

// Register continuousQuery on server 
cache.MessagingService.RegisterCQ(cQuery);

For further details, you can see how to use continuous query in cache docs.

Event Notifications

Event notifications are registered by the client applications for the cache activities they are interested in. On registering events with a specific item in the cache, the client application is notified of any of the common cache operations such as add, insert, remove, and cache clear. The client application can reside anywhere and receive the event notifications for as long as it stays connected. NCache provides filters with events which are used to specify the amount of information returned with the event. These filters are None(default), Metadata and DataWithMetadata.

Moreover, NCache provides the following types of events:

  • Item Level Events:If you want to be notified about a limited set of data rather than every operation performed on the cache you can use Item level events by specifying the key/keys. Event will be triggered on any update on the specific cache item. Similarly, if the item is removed, an event is triggered based on the callback.
  • Cache Level Events: Cache level events are the general events that can be useful when all the client applications need to be notified about any modification in the cache by any connected client application.

The code given below shows registering cache level events for any item added to the cache.

// Register target method
var dataNotificationCallback = new CacheDataNotificationCallback(OnCacheDataModification);

// Register cache notification with "ItemAdded" EventType  
// and "DataWithMetadata" as the EventDataFilter
CacheEventDescriptor eventDescriptor = cache.MessagingService.RegisterCacheNotification(dataNotificationCallback, EventType.ItemAdded, EventDataFilter.DataWithMetadata);

This is how a callback is created to be registered for any modification in the cache data. 
public static void OnCacheDataModification(string key, CacheEventArg args)
{
    switch (args.EventType)
    {
        case EventType.ItemAdded:
            // 'key' has been added to the cache
        break;
    }
}

Why NCache?

For .NET / .NET Core applications, NCache is the ideal choice for doing high transaction Pub/Sub Messaging, Continuous Query, and Events. Here is why.

  • Extremely Fast & Scalable: NCache is extremely fast due to being in-memory and gives you sub-millisecond response times. Moreover, it is a distributed cache that lets you add servers to the cache cluster to achieve linear scalability and handle extreme transaction loads.
  • High Availability thru Data Replication: NCache intelligently replicates data in the cache without compromising performance. So, you won't lose any data (events and messages) even if a cache server goes down.
  • 100% .NET / .NET Core: For .NET application, NCache offers a completely native stack to integrate with. Unlike other solutions that may have a .NET API but often require Linux deployments or unsupported Windows "ports", NCache is 100% committed to .NET / .NET Core and fits into your application stack seamlessly.

With this, you can use NCache as a powerful yet simple messaging platform. Read more about NCache from the links below and download a fully working 60-day trial.

What to Do Next?

Signup for monthly email newsletter to get latest updates.

Contact Us

PHONE

+1 (214) 764-6933 (US)

+44 20 7993 8327 (UK)

© Copyright Alachisoft 2002 - . All rights reserved.