Subscribe for Topic Messages
The ITopic
interface facilitates creating subscription and publishing of messages against the topic. This also provides event registrations for message delivery failure, receiving messages and deleting topics.
The CreateSubscription method registers against the topic if the topic exists. It allows the subscriber to register MessageReceivedCallback
against the topic so that it can receive the published messages.
Pre-Requisites for Publishing Message
- Include the following namespace in your application:
Alachisoft.NCache.Web.Caching
Alachisoft.NCache.Runtime
- The application must be connected to cache before performing the operation.
- Cache must be running.
- Make sure that the data being added is serializable.
- To ensure the operation is fail safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
The following code sample does the following:
- Get existing topic of interest –
orderTopic
. - Create subscription for each topic.
- Register events for subscribers to receive messages once published to the topic.
- Unsubscribe subscribers registered to
orderTopic
.
try
{
// Pre-Condition: Cache is already connected
// orderTopic is the name of the topic created beforehand
string topicName = "orderTopic";
// Get the topic
ITopic orderTopic = cache.MessagingService.GetTopic(topicName);
if (orderTopic != null)
{
// Create and register subscribers for Order topic
ITopicSubscription ordSubscriber1 = orderTopic.CreateSubscription(MessageReceived);
// Topics can also be unsubscribed
// ordSubscriber1.UnSubscribe();
}
else
{
// No topic exists
}
}
catch (OperationFailedException ex)
{
if (ex.Message.Contains("Topic 'orderTopic' is disposed."))
{
// orderTopic does not exist
}
else
{
// Exception can occur due to:
// Connection Failures
// Operation performed during state transfer
// Operation Timeout
}
}
catch (Exception ex)
{
// Any other generic exception like ArgumentNullException or ArgumentException
}
private void MessageReceived(object sender, MessageEventArgs args)
{
// Perform operations
if(args.Message.Payload is Order ord)
{
// Perform operations
}
else
{
// Messaage failed to receive
}
}
Recommendation: To ensure the operation is fail safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
See Also
Cache Events
Pub/Sub Topics
Pub/Sub Messages
Publish Messages to Topic
Continuous Query