Publish Message to Topic
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.
It provides the Publish method which publishes the message in the cache. It allows the user to specify the message delivery option using an enum DeliveryOption which has two options:
All (1): Delivers message to all the registered subscribers.
Any (0): Delivers the message to any one of the registered subscribers.
Moreover, it allows the publisher to get notified if the message has failed to deliver because of any issue using the
notifyDeliveryFailure
flag.
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:
- Create dedicated topics for Order related messages.
- Register
MessageDeliveryFailure
event for topic. - Register
OnTopicDeleted
event for topic. - Create messages for each topic, enabling expiration and delivery options.
- Publish the messages.
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 the object to be sent in message
Order order = FetchOrderFromDB(10248);
// Create the new message with the object order
Message orderMessage = new Message(order);
// Set the expiration time of the message
orderMessage.ExpirationTime = TimeSpan.FromSeconds(5000);
// Register message delivery failure
orderTopic.MessageDeliveryFailure += OnFailureMessageRecieved;
//Register topic deletion notification
orderTopic.OnTopicDeleted = TopicDeleted;
// Publish the order with delivery option set as all
// and register message delivery failure
orderTopic.Publish(orderMessage, DeliveryOption.All, true);
}
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
}
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
Subscribe for Topic Messages
Continuous Query