titolo: messaggistica Pub/Sub: iscriviti a un argomento descrizione: scopri come iscriverti ai messaggi di argomento quando utilizzi la cache come archivio di messaggistica Pub/Sub.
Messaggistica Pub/Sub: Iscriviti a un argomento
Nel modello di messaggistica Pub/Sub l'abbonato (o l'applicazione client) può registrarsi a un argomento particolare tramite una sottoscrizione. COSÌ, NCache fornisce più tipi di abbonamenti agli argomenti Pub/Sub.
Messaggistica Pub/Sub: Prerequisiti Sottoscrizione all'argomento
Prima di sottoscrivere un argomento nel modello di messaggistica Pub/Sub, assicurarsi che siano soddisfatti i seguenti prerequisiti:
- Per conoscere i prerequisiti standard richiesti per lavorare con all NCache caratteristiche lato client si prega di fare riferimento alla pagina indicata su Prerequisiti dell'API lato client.
- Per i dettagli dell'API, fare riferimento a: ICache, CacheItem, Argomento, IDurableTopicSubscription, Crea abbonamento, Creaabbonamento durevole,Nome argomento, NomeAbbonamento, IMessagingService, GetTopic, Politica di abbonamento, Annulla l'iscrizione, MessageEventArgs, Modalità di consegna, Argomenti Opzioni di ricerca, ITopicAbbonamento, Errore di consegna del messaggio, Carico utile.
- Per conoscere i prerequisiti standard richiesti per lavorare con all NCache caratteristiche lato client si prega di fare riferimento alla pagina indicata su Prerequisiti dell'API lato client.
- Per i dettagli dell'API, fare riferimento a: Cache, CacheItem, Argomento, Sottoscrizione all'argomento, getMessagingService, getTopic, createDurableSubscription, Politica di abbonamento, Intervallo di tempo, Annulla l'iscrizione, Ascoltatore del messaggio ricevuto, onMessaggio ricevuto, MessageEventArgs, getMessage, getPayload, createSubscription, Modalità di consegna, Argomenti Opzioni di ricerca, addMessageDeliveryFailureListener.
- Per conoscere i prerequisiti standard richiesti per lavorare con all NCache caratteristiche lato client si prega di fare riferimento alla pagina indicata su Prerequisiti dell'API lato client.
- Per i dettagli dell'API, fare riferimento a: Cache, CacheItem, Sottoscrizione all'argomento, getMessagingService, getTopic, createDurableSubscription, Politica di abbonamento, Intervallo di tempo, Annulla l'iscrizione, MessageEventArgs, Ascoltatore del messaggio ricevuto, getMessage, getPayload, createSubscription, Modalità di consegna, Argomenti Opzioni di ricerca, Ascoltatore di argomenti, addMessageDeliveryFailureListener.
- Per conoscere i prerequisiti standard richiesti per lavorare con all NCache caratteristiche lato client si prega di fare riferimento alla pagina indicata su Prerequisiti dell'API lato client.
- Per i dettagli dell'API, fare riferimento a: Cache, CacheItem, get_topic, get_messaging_service, create_durable_subscription, get_carico utile, Intervallo di tempo, MessageEventArgs, ricevi_messaggio, crea_abbonamento, Annulla l'iscrizione, add_message_delivery_failure_listener.
Metodi per creare un abbonamento
Qui descriviamo come creare abbonamenti non durevoli, abbonamenti durevoli, abbonamenti multipli e abbonamenti asincroni nel modello di messaggistica Pub/Sub.
Abbonamenti non durevoli
Note:
Questa funzionalità è disponibile anche in NCache Professional.
I ITopic
/Topic
l'interfaccia facilita la creazione abbonamento non durevole e pubblicazione di messaggi contro l'argomento. Il metodo di creazione della sottoscrizione registra una sottoscrizione non durevole rispetto a un argomento se l'argomento esiste. Permette all'abbonato di registrarsi MessageReceivedCallback
contro l'argomento in modo che possa ricevere i messaggi pubblicati.
L'esempio di codice seguente esegue le seguenti operazioni:
- Ottieni argomento di interesse esistente, ad es
NewBeverages
.
- Crea una sottoscrizione per ogni argomento.
- Registra gli eventi per consentire agli iscritti di ricevere messaggi una volta pubblicati sull'argomento.
// 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:
Per garantire che l'operazione sia a prova di errore, si consiglia di gestire eventuali potenziali eccezioni all'interno dell'applicazione, come spiegato in Gestione dei guasti.
Abbonamenti durevoli
Note:
Questa funzionalità è disponibile anche in NCache Professional.
I IDurableTopicSubscription
l'interfaccia facilita la creazione abbonamenti durevoli e pubblicare messaggi contro l'argomento se esiste. Consente all'abbonato di registrare a MessageReceivedCallback
contro l'argomento, in modo che possa ricevere i messaggi pubblicati.
Abbonamenti durevoli condivisi
Il codice seguente illustra i criteri di sottoscrizione condivisi.
// 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));
Abbonamenti durevoli esclusivi
Il codice seguente illustra i criteri di sottoscrizione esclusiva.
// 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))
Abbonamenti multipli
Utilizzando questo metodo di abbonamento, gli abbonati possono fornire modelli per iscriversi a più argomenti con un'unica chiamata. Per questo è importante che gli argomenti corrispondenti al modello esistano già sul server. Una volta che le sottoscrizioni sono state create con successo sull'argomento basato sul modello, gli abbonati ricevono i messaggi pubblicati sugli argomenti che corrispondono al modello. Inoltre, se un argomento viene creato dopo che la sottoscrizione basata su modello è stata registrata rispetto al modello, il sottoscrittore verrà registrato rispetto a quell'argomento.
Allo stesso modo, per quanto riguarda l'annullamento della registrazione da un argomento, questo metodo annulla l'iscrizione dell'abbonato a tutti gli argomenti corrispondenti con il modello fornito senza influenzare qualsiasi altra iscrizione che utilizza questa chiamata.
Note:
- Un abbonato può ottenere solo un argomento basato su pattern e non è autorizzato a crearlo.
- Un modello può essere utilizzato dall'editore solo per ricevere notifiche di errore.
Caratteri jolly supportati
Il metodo di sottoscrizione basato su pattern supporta i seguenti tre caratteri jolly:
*
: zero o più caratteri. Per esempio, bl*
si iscrive a nero, blu e sfocatura ecc.
?
: qualsiasi carattere. Per esempio, h?t
si iscrive a hit, hot e hat ecc.
[]
: gamma di caratteri. Per esempio, b[ae]t
si iscrive a bet e bat, ma non bit.
Creazione di un abbonamento con caratteri jolly
L'esempio seguente crea una sottoscrizione fornendo un modello in base al quale viene sottoscritto l'argomento corrispondente al modello.
// 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)
Abbonamenti asincroni
La modalità di consegna può essere specificata durante la creazione di abbonamenti per i messaggi ordinati e può esserlo sync
or async
. L'esempio seguente crea la sottoscrizione utilizzando CreateSubscription
metodo con modalità di consegna sincronizzata. Si consiglia di utilizzare sync
modalità per i messaggi ordinati e async
modalità altrimenti per ottenere prestazioni elevate.
Durante la creazione di una sottoscrizione, è possibile specificare la modalità di consegna che può essere sincrona o asincrona. In particolare, è possibile utilizzare la modalità di consegna sincrona messaggi ordinati, mentre se non si utilizzano messaggi ordinati, la modalità asincrona migliora le prestazioni.
Note:
Per impostazione predefinita, la modalità di consegna dei messaggi è impostata su sincrona.
// 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:
Puoi anche annullare l'iscrizione a un argomento.
Risorse addizionali
NCache fornisce un'applicazione di esempio per Pub/Sub su GitHub.
Vedere anche
.NETTO: Alachisoft.NCache.Memorizzazione.della.cache spazio dei nomi.
Giava: com.alachisoft.ncache.cache.di.runtime spazio dei nomi.
Node.js: Classe TopicSubscription classe.
Pitone: ncache.servizi.clienti classe.