title: Mensagens do Pub/Sub: Inscrever-se em um tópico description: Saiba como se inscrever em mensagens de tópico ao usar o cache como um armazenamento de mensagens do Pub/Sub.
Mensagens do Pub/Sub: inscreva-se em um tópico
No modelo de mensagens do Pub/Sub, o assinante (ou aplicativo cliente) pode registrar-se em um tópico específico por meio de uma assinatura. Então, NCache fornece múltiplos tipos de assinaturas de tópicos do Pub/Sub.
Mensagens do Pub/Sub: pré-requisitos para assinatura de tópico
Antes de assinar um tópico no modelo de mensagens do Pub/Sub, certifique-se de que os seguintes pré-requisitos sejam atendidos:
- Para aprender sobre os pré-requisitos padrão necessários para trabalhar com todos os NCache recursos do lado do cliente, consulte a página fornecida em Pré-requisitos da API do lado do cliente.
- Para obter detalhes da API, consulte: ICache, Item de cache, Tópico, IDurableTopicSubscrição, CriarAssinatura, CriarAssinaturaDurável,Nome do tópico, Nome da assinatura, Serviço de mensagens, Obter tópico, Política de assinatura, Cancelar subscrição, MensagemEventArgs, Modo de entrega, Opções de pesquisa de tópicos, Assinatura ITopic, Falha na entrega da mensagem, Payload.
- Para aprender sobre os pré-requisitos padrão necessários para trabalhar com todos os NCache recursos do lado do cliente, consulte a página fornecida em Pré-requisitos da API do lado do cliente.
- Para obter detalhes da API, consulte: Esconderijo, Item de cache, Tema, Assinatura do tópico, getMessagingService, getTopic, criarDurableSubscription, Política de assinatura, Intervalo de tempo, Cancelar subscrição, Ouvinte de mensagem recebida, onMessageReceived, MensagemEventArgs, getMensagem, getPayload, criarAssinatura, Modo de entrega, Opções de pesquisa de tópicos, addMessageDeliveryFailureListener.
- Para aprender sobre os pré-requisitos padrão necessários para trabalhar com todos os NCache recursos do lado do cliente, consulte a página fornecida em Pré-requisitos da API do lado do cliente.
- Para obter detalhes da API, consulte: Esconderijo, Item de cache, Assinatura do tópico, getMessagingService, getTopic, criarDurableSubscription, Política de assinatura, Intervalo de tempo, Cancelar subscrição, MensagemEventArgs, Ouvinte de mensagem recebida, getMensagem, getPayload, criarAssinatura, Modo de entrega, Opções de pesquisa de tópicos, Topic Listener, addMessageDeliveryFailureListener.
- Para aprender sobre os pré-requisitos padrão necessários para trabalhar com todos os NCache recursos do lado do cliente, consulte a página fornecida em Pré-requisitos da API do lado do cliente.
- Para obter detalhes da API, consulte: Esconderijo, Item de cache, get_topic, get_messaging_service, criar_durável_subscrição, get_payload, Intervalo de tempo, MensagemEventArgs, obter_mensagem, criar_assinatura, Cancelar subscrição, add_message_delivery_failure_listener.
Métodos para criar uma assinatura
Aqui descrevemos como você pode criar assinaturas não duráveis, assinaturas duráveis, várias assinaturas e assinaturas assíncronas no modelo de mensagens do Pub/Sub.
Assinaturas não duráveis
Note
Este recurso também está disponível em NCache Professional.
A ITopic
/Topic
interface facilita a criação assinatura não durável e publicação de mensagens sobre o tema. O método create subscription registra uma assinatura não durável em um tópico, se o tópico existir. Permite que o assinante se cadastre MessageReceivedCallback
contra o tópico para que ele possa receber as mensagens publicadas.
O exemplo de código a seguir faz o seguinte:
- Obter tópico de interesse existente, ou seja,
NewBeverages
.
- Crie uma assinatura para cada tópico.
- Registre eventos para que os assinantes recebam mensagens uma vez publicadas no tópico.
// 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.");
}
// 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 topic
// Message received callback is specified
let ordersubscriber = await ordertopic.createSubscription(ncache.onMessageReceived());
}
else {
// No topic exists
}
# 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")
Note
Para garantir que a operação seja à prova de falhas, é recomendável lidar com possíveis exceções em seu aplicativo, conforme explicado em Como lidar com falhas.
Assinaturas duráveis
Note
Este recurso também está disponível em NCache Professional.
A IDurableTopicSubscription
interface facilita a criação assinaturas duráveis e publicar mensagens sobre o tópico, se ele existir. Permite ao assinante cadastrar um MessageReceivedCallback
contra o tema, para que possa receber as mensagens publicadas.
Assinaturas duráveis compartilhadas
O código a seguir demonstra a política de assinatura compartilhada.
// 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 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));
// 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));
Assinaturas duráveis exclusivas
O código a seguir demonstra a política de assinatura exclusiva.
// 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
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));
# 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))
Múltiplas Assinaturas
Usando esse método de assinatura, os assinantes podem fornecer padrões para assinar vários tópicos com uma única chamada. Para isso, é importante que os tópicos correspondentes ao padrão já existam no servidor. Depois que as assinaturas são criadas com sucesso no tópico baseado em padrão, os assinantes recebem mensagens publicadas em tópicos que correspondem ao padrão. Além disso, se um tópico for criado após a assinatura baseada em padrão ter sido registrada no padrão, ele registrará esse assinante nesse tópico.
Da mesma forma, em relação ao cancelamento do registro de um tópico, este método cancela a assinatura do assinante em todos os tópicos correspondentes com o padrão fornecido, sem afetar qualquer outra assinatura que use esta chamada.
Note
- Um assinante só pode obter um tópico baseado em padrão e não tem permissão para criá-lo.
- Um padrão pode ser usado pelo editor apenas para receber notificações de falha.
Curingas compatíveis
O método de assinatura baseado em padrão oferece suporte aos três curingas a seguir:
*
: zero ou muitos caracteres. Por exemplo, bl*
assina preto, azul e borrão etc.
?
: qualquer caractere. Por exemplo, h?t
assina hit, hot e hat etc.
[]
: intervalo de caracteres. Por exemplo, b[ae]t
se inscreve para apostar e bat, mas não pouco.
Criando uma assinatura com curinga
O exemplo a seguir cria uma assinatura fornecendo um padrão com base no qual o tópico está inscrito correspondendo ao padrão.
// 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
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());
# 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)
Assinaturas assíncronas
O modo de entrega pode ser especificado ao criar assinaturas para mensagens solicitadas e pode ser sync
or async
. O exemplo a seguir cria assinatura usando CreateSubscription
método com o modo de entrega de sincronização. Recomenda-se usar sync
modo para mensagens ordenadas e async
modo de outra forma para alcançar alto desempenho.
Ao criar uma assinatura, você pode especificar o modo de entrega que pode ser síncrono ou assíncrono. Em particular, o modo de entrega síncrona pode ser usado para mensagens ordenadas, enquanto que se você não estiver usando mensagens ordenadas, o modo assíncrono melhora o desempenho.
Note
Por padrão, o modo de entrega das mensagens é definido como síncrono.
// 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.");
}
// 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
}
# 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")
Note
Você também pode cancelar a assinatura de um tópico.
Recursos adicionais
NCache fornece aplicativo de amostra para Pub/Sub em GitHub.
Veja também
.INTERNET: Alachisoft.NCache.Runtime.Cache espaço para nome.
Java: com.alachisoft.ncache.runtime.caching espaço para nome.
Node.js: Classe de Assinatura de Tópico classe.
Pitão: ncache.Serviço para clientes classe.