Pub/Sub Messaging, Continuous Query and Events

Many server applications today need to coordinate work with other applications and share messages and data in an asynchronous manner 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. The components of Pub/Sub messaging in NCache are explained briefly below:

  • Publisher: An application that publishes the message to be consumed by multiple subscribers without knowing the subscriber(s). It receives a failure notification on message delivery failure.
  • Subscriber: an application that registers itself to receive messages against a specific topic of interest without knowing the publisher.
  • Topic: this is a category of messages and also called a channel through which the publisher and subscriber communicate with each other via messages. It stores the actual data object published by the publisher and internally maintains a list of subscribers.
  • Message: this is the actual message sent by publishers and received by the subscribers interested.
  • Types of Subscriptions:
    • Durable/Non-Durable Subscriptions: Durable subscriptions ensure that the subscribers receive the corresponding messages in all cases such as disconnection or reconnection. It has further two types i.e. exclusive and shared subscriptions. Exclusive subscriptions are the ones which have only one active subscriber at a time and shared subscriptions are the ones where more than one subscriber can subscribe at a time. However, in non-durable subscriptions, the messages are only delivered until the specific subscriber stays connected. If a subscriber is temporarily disconnected under any circumstances, it does not receive the messages published in the duration of disconnection on reestablishing the connection.
    • Pattern Based Subscriptions: In this kind of subscription, the subscriber can provide patterns to subscribe to the multiple topics matching the pattern
Pub/Sub Messaging with NCache

Below is a source code example on how a Publisher publishes a message against at 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

Continuous Query (CQ)

Continuous query is a feature provided by NCache for monitoring data changes in the cache based on an 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 change occurring in the cache.

  • Add: Addition of an item in the cache which fulfils 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 fulfils the query criteria. Returns either the entire object or its key and meta-data.
string sql = "SELECT Alachisoft.NCache.Sample.Data.Customer WHERE this.Country = ?";

values["Country"] = "USA";
ContinuousQuery query = new ContinuousQuery(sql, values);

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

// Register continuous query with the cache

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 on any of the common cache operation 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. NCache provides following types of events:

  • Item Level Events: Item level events are specific to a single item identified by a key. 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 triggered on any operation performed in the entire cache such as item added, updated or removed. The purpose of cache level events is for all the client applications to know about any modification in the cache by any client application connected.

The code given below shows registering cache level events for any item removed from 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

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 totally 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


+1 (214) 764-6933 (US)

+44 20 7993 8327 (UK)

© Copyright Alachisoft 2002 - . All rights reserved.