Managing Topics
The following examples show how topics can be created, fetched and deleted using the APIs discussed previously.
In order to utilize messaging APIs, include the following namespaces in your application:
Alachisoft.NCache.Web.Caching
Alachisoft.NCache.Runtime.Caching
Create Topic
The following code sample creates a topic orderTopic in cache named pubSubCache. If the topic of the same name exists, it will return an instance of that topic.
string cacheName = "pubSubCache";
string topicName = "orderTopic";
Cache cache = NCache.InitializeCache(cacheName);
cache.MessagingService.CreateTopic(topicName);
Get Topic
The following code sample gets an existing topic orderTopic from
pubSubCache and creates a subscription against it while registering a
MessageReceivedCallback
for receiving messages. If no topic exists, it will return null.
string cacheName = "pubSubCache";
string topicName = "orderTopic";
Cache cache = NCache.InitializeCache(cacheName);
ITopic productTopic = cache.MessagingService.GetTopic(topicName);
ITopicSubscription prodSubscriber = productTopic.CreateSubscription(MessageReceived);
private void MessageReceived(object sender, MessageEventArgs args)
{
//perform operations
}
Delete Topic
The following code sample deletes the existing topic orderTopic from
pubSubCache and removes all messages associated with that topic. If the OnTopicDeleted
callback is registered, it will be triggered upon this method call.
string cacheName = "pubSubCache";
string topicName = "orderTopic";
Cache cache = NCache.InitializeCache(cacheName);
cache.MessagingService.DeleteTopic(topicName);