Publish Message to Topic
In order to utilize messaging APIs, include the following namespaces in your application:
Alachisoft.NCache.Web.Caching
Alachisoft.NCache.Runtime.Caching
The following code sample does the following:
- Initialize dedicated Pub/Sub cache.
- 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.
public void PublishMessages()
{
string cacheName = "pubSubCache";
string topicName = "orderTopic";
Cache cache = NCache.InitializeCache(cacheName);
ITopic orderTopic = cache.MessagingService.CreateTopic(topicName);
//Register message failure notification
orderTopic.MessageDeliveryFailure += FailureMessageReceived;
//Register topic deletion notification
orderTopic.OnTopicDeleted = TopicDeleted;
//Payload to be sent in message
Order payload = new Order();
payload.OrderID = 10248;
payload.OrderDate = new DateTime(2015,07,04);
payload.ShipName = "Vins et alcools Chevalier";
payload.ShipAddress = "59 rue de l'Abbaye";
payload.ShipCity = "Reims";
payload.ShipCountry = "France";
//Create message with Order and expiration time set to 150 seconds
Message orderMessage = new Message(orderPayload);
orderMessage.ExpirationTime = new TimeSpan(0, 0, 150);
//Publish message to all registered subscribers
//and register message delivery failure notification
orderTopic.Publish(orderMessage, DeliveryOption.All, true);
}
private void FailureMessageReceived(object sender, MessageFailedEventArgs args)
{
//can get failure reason through args.MessgeFailureReason
}
private void TopicDeleted(object sender, TopicDeleteEventArgs args)
{
//can get deleted topic name through args.TopicName
}