Try Playground
Show / Hide Table of Contents

Pub/Sub Messaging: Subscribe to a Topic

In Pub/Sub messaging model, subscriber (or client application) can register to a particular Topic through a subscription. So, NCache provides multiple types of Pub/Sub Topic subscriptions.

Pub/Sub Messaging: Prerequisites Topic Subscription

Before subscribing a Topic in Pub/Sub Messaging model, ensure that the following prerequisites are fulfilled:

  • .NET
  • Java
  • Python
  • Node.js
  • Legacy API
  • To learn about the standard prerequisites required to work with all NCache client-side features, please refer to the given page on Client-Side API Prerequisites.
  • For API details, refer to: ICache, CacheItem, ITopic, IDurableTopicSubscription, CreateSubscription, CreateDurableSubscription,TopicName, SubscriptionName, IMessagingService, GetTopic, SubscriptionPolicy, UnSubscribe, MessageEventArgs, DeliveryMode, TopicSearchOptions, ITopicSubscription, MessageDeliveryFailure, PayLoad.
  • To learn about the standard prerequisites required to work with all NCache client-side features, please refer to the given page on Client-Side API Prerequisites.
  • For API details, refer to: Cache, CacheItem, Topic, TopicSubscription, getMessagingService, getTopic, createDurableSubscription, SubscriptionPolicy, TimeSpan, unSubscribe, MessageReceivedListener, onMessageReceived​, MessageEventArgs, getMessage, getPayload, createSubscription, DeliveryMode, TopicSearchOptions, addMessageDeliveryFailureListener.
  • To learn about the standard prerequisites required to work with all NCache client-side features, please refer to the given page on Client-Side API Prerequisites.
  • For API details, refer to: Cache, CacheItem, get_topic, get_messaging_service, create_durable_subscription, get_payload, TimeSpan, MessageEventArgs, get_message, create_subscription, un_subscribe, add_message_delivery_failure_listener.
  • To learn about the standard prerequisites required to work with all NCache client-side features, please refer to the given page on Client-Side API Prerequisites.
  • For API details, refer to: Cache, CacheItem, TopicSubscription, getMessagingService, getTopic, createDurableSubscription, SubscriptionPolicy, TimeSpan, unSubscribe, MessageEventArgs, MessageReceivedListener, getMessage, getPayload, createSubscription, DeliveryMode, TopicSearchOptions, TopicListener, addMessageDeliveryFailureListener.
  • Create a new Console Application.
  • Make sure that the data being added is serializable.
  • Add NCache References by locating %NCHOME%\NCache\bin\assembly\4.0 and adding Alachisoft.NCache.Web and Alachisoft.NCache.Runtime as appropriate.
  • Include the Alachisoft.NCache.Web.Caching and Alachisoft.NCache.Runtime.Caching namespace in your application

Methods to Create a Subscription

Here we describe how you can create Non-durable Subscription, Durable Subscription, multiple subscriptions, and asynchronous subscription in Pub/Sub Messaging Model.

Non-Durable Subscriptions

Note

This feature is also available in NCache Professional.

The ITopic/Topic interface facilitates creating a non-durable subscription and publishing of messages against the Topic. The create subscription method registers a Non-durable Subscription against a Topic if the topic exists. It allows the subscriber to register MessageReceivedCallback against the Topic so that it can receive the published messages.

The following code sample does the following:

  1. Get existing topic of interest, i.e., NewBeverages.
  2. Create subscription for each topic.
  3. Register events for subscribers to receive messages once published to the Topic.
  • .NET
  • Java
  • Python
  • Node.js
  • Legacy API
// Precondition: Cache is already connected

// NewBeverages is the name of the topic created, beforehand
string topicName = "NewBeverages";

// Get the topic
ITopic topic = cache.MessagingService.GetTopic(topicName);

// If topic exists, Create subscription
if (topic != null)
{
    // Create and register subscribers for order topic
    // Message received callback is specified
    ITopicSubscription subscription = topic.CreateSubscription(MessageReceived);
}
// Precondition: Cache is already connected

// NewBeverages is the name of the topic created beforehand
String topicName = "NewBeverages";

// Get the topic
Topic ordertopic = cache.getMessagingService().getTopic(topicName);

// If topic exists, Create subscription
if (ordertopic != null) {
    // Create and register subscribers for order topic
    ordertopic.createSubscription(new PubSubMessageReceivedListener());
    System.out.println("Subscriber registered for topic: " + ordertopic.getName());
} else {
    System.out.println("Topic does not exist.");
}
# Precondition: Cache is already connected
# Topic "NewBeverages" already exists in the cache
topic_name = "NewBeverages"

# Get the topic
order_topic = cache.get_messaging_service().get_topic(topic_name)

if order_topic is not None:
    # Create and register subscribers for the topic
    # Message received callback is specified
    order_subscriber = order_topic.create_subscription(on_message_received)
else:
    # No topic exists
    print("Topic not found")
// This is an async method
// Precondition: Cache is already connected

// Topic "NewBeverages" already exists in the cache
let topicName = "NewBeverages";

// Get the topic
let ordertopic = await ncache.getMessagingService().getTopic(topicName);

if (ordertopic != null) {
    // Create and register subscribers for topic
    // Message received callback is specified
    let ordersubscriber = await ordertopic.createSubscription(ncache.onMessageReceived());
}
else {
    // No topic exists
}
public void Subscribe()
{
    string cacheName = "pubSubCache";
    string topicName = "orderTopic";

    Cache cache = NCache.InitializeCache(cacheName);

    //Get Order topic
    ITopic orderTopic = cache.MessagingService.GetTopic(topicName);

    //Register subscribers for Order topic
    ITopicSubscription ordSubscriber1 = orderTopic.CreateSubscription(MessageReceived);
    ITopicSubscription ordSubscriber2 = orderTopic.CreateSubscription(MessageReceived);

    //Unsubscribe Order subscribers
    ordSubscriber1.UnSubscribe();
    ordSubscriber2.UnSubscribe();
}

private void MessageReceived(object sender, MessageEventArgs args)
{
    //perform operations

    if(args.Message.Payload is Order ord)
    {
        //perform operations
    }
}
Note

To ensure the operation is fail-safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.

Durable Subscriptions

Note

This feature is also available in NCache Professional.

The IDurableTopicSubscription interface facilitates creating Durable subscriptions and publishing messages against the Topic if it exists. It allows the subscriber to register a MessageReceivedCallback against the Topic, so that it can receive the published messages.

Shared Durable Subscriptions

The following code demonstrates the Shared Subscription policy.

  • .NET
  • Java
  • Python
  • Node.js
// DiscountedBeverages is the name of the topic created, beforehand
string topicName = "DiscountedBeverages";

string subscriptionName = "DiscountedBeveragesSubscription";

// Get the topic
ITopic ordertopic = cache.MessagingService.GetTopic(topicName);

if (ordertopic != null)
{
    // Create and register subscribers for topic
    // Message received callback is specified
    // The subscription policy is shared which means that the subscription can have more than one subscribers
    IDurableTopicSubscription ordersubscription = ordertopic.CreateDurableSubscription (subscriptionName, SubscriptionPolicy.Shared, MessageReceived, TimeSpan.FromMinutes(20));
}
// DiscountedBeverages is the name of the topic created beforehand
String topicName = "DiscountedBeverages";
Topic ordertopic = cache.getMessagingService().getTopic(topicName);

// Get the topic
if (ordertopic != null) {
    // Create and register subscribers for topic
    // The subscription policy is shared which means that the subscription can have more than one subscribers
    System.out.println("Topic retrieved: " + ordertopic.getName());
    ordertopic.createDurableSubscription(subscriptionName, SubscriptionPolicy.Shared, new PubSubMessageReceivedListener(), TimeSpan.FromMinutes(20));
    System.out.println("Durable subscriber registered for topic: " + ordertopic.getName());
} else {
    System.out.println("Topic does not exist.");
}
# Topic "DiscountedBeverages" already exists in the cache
let topicName = "DiscountedBeverages";
let subscriptionName = "DiscountedBeveragesSubscription";

# Get the topic
let orderTopic = ncache.getMessagingService().getTopic(topicName);

# Create and register subscribers for orderTopic
# MessageReceived callback is specified below
# The subscription policy is Shared which means that the subscription can have more than one subscribers
let orderSubscriber = orderTopic.createDurableSubscription(subscriptionName, ncache.SubscriptionPolicy.Shared, this.messageReceived(), ncache.TimeSpan.FromMinutes(20));
// Topic "DiscountedBeverages" already exists in the cache
let topicName = "DiscountedBeverages";
let subscriptionName = "DiscountedBeveragesSubscription";

// Get the topic
let ordertopic = ncache.getMessagingService().getTopic(topicName);

// Create and register subscribers for order Topic
// Message received callback is specified below
// The subscription policy is Shared which means that the subscription can have more than one subscribers
let orderSubscriber = orderTopic.createDurableSubscription(subscriptionName, ncache.SubscriptionPolicy.Shared, this.messageReceived(), ncache.TimeSpan.FromMinutes(20));

Exclusive Durable Subscriptions

The following code demonstrates the Exclusive Subscription policy.

  • .NET
  • Java
  • Python
  • Node.js
// orderTopic is the name of the topic created beforehand
string topicName = "orderTopic";

string subscriptionName = "orderTopicName";

// Get the topic
ITopic orderTopic = cache.MessagingService.GetTopic(topicName);

// Create and register subscribers for Order topic
// The subscription policy is exclusive which means that the subscription can have only one subscriber
IDurableTopicSubscription orderSubscriber = orderTopic.CreateDurableSubscription(subscriptionName, SubscriptionPolicy.Exclusive, MessageReceived, TimeSpan.FromMinutes(20));
// Get the topic
Topic orderTopic = cache.getMessagingService().getTopic(topicName);

if (orderTopic != null) {
    System.out.println("Topic retrieved: " + orderTopic.getName());

    // Create and register subscribers for Order topic
    // The subscription policy is exclusive which means that the subscription can have only one subscriber
    orderTopic.createDurableSubscription(subscriptionName,SubscriptionPolicy.Exclusive, new PubSubMessageReceivedListener(),TimeSpan.FromMinutes(20));
    System.out.println("Durable subscriber registered for topic: " + orderTopic.getName());
} else {
    System.out.println("Topic does not exist.");
}
# Topic "orderTopic" already exists in the cache
topic_name = "orderTopic"
subscription_name = "orderTopicName"

# Get the topic
order_topic = cache.get_messaging_service().get_topic(topic_name)

# Create and register subscribers for orderTopic
# The subscription policy is exlusive which means that the subscription can have more than one subscriber
order_subscriber = order_topic.create_durable_subscription(subscription_name, ncache.SubscriptionPolicy.EXCLUSIVE, on_message_received, ncache.TimeSpan.from_minutes(20))
// Topic "orderTopic" already exists in the cache
let topicName = "orderTopic";
let subscriptionName = "orderTopicName";

// Get the topic
let orderTopic = ncache.getMessagingService().getTopic(topicName);

// Create and register subscribers for orderTopic
// The subscription policy is Exclusive which means that the subscription can have more than one subscribers
let orderSubscriber = orderTopic.createDurableSubscription(subscriptionName, ncache.SubscriptionPolicy.Exclusive, this.messageReceived(), ncache.TimeSpan.FromMinutes(20));

Multiple Subscriptions

Using this method of subscription, subscribers can provide patterns to subscribe to multiple topics with a single call. For this, it is important that the topics matching the pattern already exist on the server. Once the subscription(s) is/are successfully created on the pattern-based topic, the subscribers receive messages published on topics that match the pattern. Also, if a Topic is created after the pattern-based-subscription has been registered against the pattern, it will register that subscriber against that Topic.

Similarly, regarding unregistering from a Topic, this method unsubscribes the subscriber against all the matching topics with provided pattern without affecting any other subscription using this call.

Note
  • A subscriber can only get pattern-based topic and is not allowed to create it.
  • A pattern can be used by the publisher only to receive failure notifications.

Supported Wildcards

Pattern-based method of subscription supports the following three wildcards:

  1. * : Zero or many characters. For example, bl* subscribes to black, blue, and blur, etc.
  2. ? : Any one character. For example, h?t subscribes to hit, hot and hat, etc.
  3. [] : Range of characters. For example, b[ae]t subscribes to bet and bat, but not bit.

Creating a Subscription with Wildcard

The following example creates a subscription by providing a pattern based on which the Topic is subscribed matching the pattern.

  • .NET
  • Java
  • Python
  • Node.js
// Create topic name for all topics with suffix Beverages
// Only ? * [] wildcards supported
string topicName = "*Beverages";

// Get the topic
ITopic topic = cache.MessagingService.GetTopic(topicName, TopicSearchOptions.ByPattern);

// If topic exists, Create subscription
if (topic != null)
{
    // Create and register subscribers for Order topic
    ITopicSubscription subscription = topic.CreateSubscription(MessageReceived);
}
// Define topic name pattern
String topicNamePattern = "*ages";

// Get all topics that fulfill the pattern
Topic topic = cache.getMessagingService().getTopic(topicNamePattern, TopicSearchOptions.ByPattern);

if (topic != null) {
    System.out.println("Matching topic retrieved: " + topic.getName());

    // Create and register notifications for topic
    topic.createSubscription(new PubSubMessageReceivedListener());
    System.out.println("Subscription created for topic: " + topic.getName());
} else {
    System.out.println("No matching topic found.");
}
# Topic "Beverages" exists in the cache
# Only ? * [] wildcards supported
topic_name = "*Beverages*"
subscription_name = "orderTopicName"

# Get the topic
order_topic = cache.get_messaging_service().get_topic(topic_name, ncache.TopicSearchOptions.BY_PATTERN)

# Create and register subscribers for orderTopic
order_subscriber = order_topic.create_subscription(on_message_received)
// Topic "Beverages" exists in the cache
// Only ? * [] wildcards supported
let topicName = "*Beverages";

// Get the topic
let orderTopic = ncache.getMessagingService().getTopic(topicName, ncache.TopicSearchOptions.ByPattern);

// Create and register subscribers for orderTopic
let orderSubscriber = orderTopic.createSubscription(this.messageReceived());

Asynchronous Subscriptions

Delivery mode can be specified while creating subscriptions for ordered messages and can be sync or async. The following example creates subscription using CreateSubscription method with sync delivery mode. It is recommended to use sync mode for ordered messages and async mode otherwise to achieve high performance.

While creating a subscription, you can specify delivery mode that can be synchronous or asynchronous. In particular, synchronous delivery mode can be used for ordered messages, whereas if you are not using ordered messages, asynchronous mode improves performance.

Note

By default, the delivery mode of messages is set to synchronous.

  • .NET
  • Java
  • Python
  • Node.js
// NewBeverages is the name of the topic created beforehand
string topicName = "NewBeverages";

// Get the topic
ITopic topic = cache.MessagingService.GetTopic(topicName);

// If topic exists, Create subscription
if (topic != null)
{
    // Create and register subscribers for Order topic
    // Message received callback is specified
    // DeliveryMode is set to async
    ITopicSubscription subscription = topic.CreateSubscription(MessageReceived, DeliveryMode.Async);
}
// NewBeverages is the name of the topic created beforehand
String topicName = "NewBeverages";

// Get the topic
Topic topic = cache.getMessagingService().getTopic(topicName);

if (topic != null) {
    // Create and register subscribers for Topic
    // Message received callback is specified
    // DeliveryMode is set to async
    topic.createSubscription(new PubSubMessageReceivedListener(),DeliveryMode.Async);
} else {
    System.out.println("Topic does not exist.");
}
# Topic "NewBeverages" already exists in the cache
topic_name = "NewBeverages"

# Get the topic
order_topic = cache.get_messaging_service().get_topic(topic_name)

if order_topic is not None:
    # Create and register subscribers for orderTopic
    # Message received callback is specified
    order_subscriber = order_topic.create_subscription(on_message_received, ncache.DeliveryMode.SYNC)
else:
    # No topic exists
    print("Topic not found")
// This is an async method
// Topic "NewBeverages" already exists in the cache
let topicName = "NewBeverages";

// Get the topic
let orderTopic = await ncache.getMessagingService().getTopic(topicName);

if (orderTopic != null) {

    // Create and register subscribers for orderTopic
    // Message received callback is specified
    let orderSubscriber = await orderTopic.createSubscription(ncache.onMessageReceived(), ncache.DeliveryMode.Sync);

    // Topics can also be unsubscribed
    orderSubscriber.unSubscribe();
}
else {
    // No topic exists
}
Note

You can also unsubscribe from a Topic.

Additional Resources

NCache provides sample application for Pub/Sub on GitHub.

See Also

.NET: Alachisoft.NCache.Runtime.Caching namespace.
Java: com.alachisoft.ncache.runtime.caching namespace.
Python: ncache.client.services class.
Node.js: TopicSubscription Class class.

In This Article
  • Pub/Sub Messaging: Prerequisites Topic Subscription
  • Methods to Create a Subscription
    • Non-Durable Subscriptions
    • Durable Subscriptions
    • Multiple Subscriptions
    • Asynchronous Subscriptions
  • Additional Resources
  • See Also

Contact Us

PHONE

+1 (214) 764-6933   (US)

+44 20 7993 8327   (UK)

 
EMAIL

sales@alachisoft.com

support@alachisoft.com

NCache
  • NCache Enterprise
  • NCache Professional
  • Edition Comparison
  • NCache Architecture
  • Benchmarks
Download
Pricing
Try Playground

Deployments
  • Cloud (SaaS & Software)
  • On-Premises
  • Kubernetes
  • Docker
Technical Use Cases
  • ASP.NET Sessions
  • ASP.NET Core Sessions
  • Pub/Sub Messaging
  • Real-Time ASP.NET SignalR
  • Internet of Things (IoT)
  • NoSQL Database
  • Stream Processing
  • Microservices
Resources
  • Magazine Articles
  • Third-Party Articles
  • Articles
  • Videos
  • Whitepapers
  • Shows
  • Talks
  • Blogs
  • Docs
Customer Case Studies
  • Testimonials
  • Customers
Support
  • Schedule a Demo
  • Forum (Google Groups)
  • Tips
Company
  • Leadership
  • Partners
  • News
  • Events
  • Careers
Contact Us

  • EnglishChinese (Simplified)FrenchGermanItalianJapaneseKoreanPortugueseSpanish

  • Contact Us
  •  
  • Sitemap
  •  
  • Terms of Use
  •  
  • Privacy Policy
© Copyright Alachisoft 2002 - 2025. All rights reserved. NCache is a registered trademark of Diyatech Corp.
Back to top