제목: Pub/Sub 메시징: 주제 구독 설명: 캐시를 Pub/Sub 메시징 저장소로 사용할 때 주제 메시지를 구독하는 방법을 알아보세요.
Pub/Sub 메시징: 주제 구독
Pub/Sub 메시징 모델에서 구독자(또는 클라이언트 애플리케이션)는 구독을 통해 특정 주제에 등록할 수 있습니다. 그래서, NCache 복수를 제공하다 Pub/Sub 주제 구독 유형.
Pub/Sub 메시징: 전제조건 주제 구독
Pub/Sub 메시징 모델에서 주제를 구독하기 전에 다음 기본 요건이 충족되는지 확인하세요.
- 모든 작업에 필요한 표준 전제 조건에 대해 알아보려면 NCache 클라이언트 측 기능은 주어진 페이지를 참조하십시오. 클라이언트 측 API 전제 조건.
- API 세부 정보는 다음을 참조하세요. 아이캐시, 캐시 아이템, 아이토픽, IDurable주제구독, 구독 만들기, CreateDurableSubscription,주제 이름, 구독 이름, 메신저 서비스, 주제 가져오기, 구독 정책, 구독 취소, 메시지 이벤트 인수, 배달 모드, 주제검색옵션, ITopic구독, 메시지 배달 실패, 유효 탑재량.
- 모든 작업에 필요한 표준 전제 조건에 대해 알아보려면 NCache 클라이언트 측 기능은 주어진 페이지를 참조하십시오. 클라이언트 측 API 전제 조건.
- API 세부 정보는 다음을 참조하세요. 캐시, 캐시 아이템, 주제, 주제구독, getMessagingService, getTopic, createDurableSubscription, 구독 정책, 시간 범위, 구독 취소, 메시지 수신 리스너, onMessageReceived, 메시지 이벤트 인수, getMessage, getPayload, 구독 생성, 배달 모드, 주제검색옵션, addMessageDeliveryFailureListener.
- 모든 작업에 필요한 표준 전제 조건에 대해 알아보려면 NCache 클라이언트 측 기능은 주어진 페이지를 참조하십시오. 클라이언트 측 API 전제 조건.
- API 세부 정보는 다음을 참조하세요. 캐시, 캐시 아이템, 주제구독, getMessagingService, getTopic, createDurableSubscription, 구독 정책, 시간 범위, 구독 취소, 메시지 이벤트 인수, 메시지 수신 리스너, getMessage, getPayload, 구독 생성, 배달 모드, 주제검색옵션, 토픽리스너, addMessageDeliveryFailureListener.
- 모든 작업에 필요한 표준 전제 조건에 대해 알아보려면 NCache 클라이언트 측 기능은 주어진 페이지를 참조하십시오. 클라이언트 측 API 전제 조건.
- API 세부 정보는 다음을 참조하세요. 캐시, 캐시 아이템, get_topic, get_messaging_service, create_durable_subscription, get_payload, 시간 범위, 메시지 이벤트 인수, get_message, create_subscription, un_subscribe, add_message_delivery_failure_listener.
구독 생성 방법
여기에서는 Pub/Sub 메시징 모델에서 비지속 구독, 지속 구독, 다중 구독, 비동기 구독을 만드는 방법을 설명합니다.
비영구 구독
주의 사항
이 기능은 다음에서도 사용할 수 있습니다. NCache Professional.
XNUMXD덴탈의 ITopic
/Topic
인터페이스는 생성을 용이하게 합니다. 비영구 구독 주제에 대한 메시지 게시. 구독 생성 메소드는 주제가 존재하는 경우 해당 주제에 대해 비지속적 구독을 등록합니다. 가입자가 등록할 수 있게 해줍니다. MessageReceivedCallback
게시된 메시지를 받을 수 있도록 주제에 대해
다음 코드 샘플은 다음을 수행합니다.
- 기존 관심 주제 가져오기
NewBeverages
.
- 각 주제에 대한 구독을 만듭니다.
- 구독자가 주제에 게시된 메시지를 수신할 이벤트를 등록합니다.
// 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")
주의 사항
작업이 안전하도록 하려면 에 설명된 대로 응용 프로그램 내에서 잠재적인 예외를 처리하는 것이 좋습니다. 처리 실패.
영구 구독
주의 사항
이 기능은 다음에서도 사용할 수 있습니다. NCache Professional.
XNUMXD덴탈의 IDurableTopicSubscription
인터페이스는 생성을 용이하게 합니다. 지속 가능한 구독 주제가 있는 경우 주제에 대한 메시지를 게시합니다. 가입자가 MessageReceivedCallback
게시된 메시지를 수신할 수 있도록 주제에 대해
지속 가능한 공유 구독
다음 코드는 공유 구독 정책을 보여줍니다.
// 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));
독점 지속 구독
다음 코드는 독점 구독 정책을 보여줍니다.
// 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))
여러 구독
이 구독 방법을 사용하면 구독자는 단일 호출로 여러 주제를 구독하는 패턴을 제공할 수 있습니다. 이를 위해서는 패턴과 일치하는 토픽이 이미 서버에 존재하는 것이 중요합니다. 패턴 기반 주제에 대한 구독이 성공적으로 생성되면 구독자는 패턴과 일치하는 주제에 게시된 메시지를 받습니다. 또한 패턴 기반 구독이 패턴에 등록된 후 토픽이 생성되면 해당 토픽에 해당 구독자가 등록됩니다.
마찬가지로, 주제 등록 취소와 관련하여 이 메서드는 이 호출을 사용하는 다른 구독에 영향을 주지 않고 제공된 패턴과 일치하는 모든 주제에 대해 구독자를 구독 취소합니다.
주의 사항
- 구독자는 패턴 기반 주제만 얻을 수 있으며 생성할 수 없습니다.
- 게시자는 실패 알림을 수신하기 위해서만 패턴을 사용할 수 있습니다.
지원되는 와일드카드
패턴 기반 구독 방법은 다음 세 가지 와일드카드를 지원합니다.
*
: XNUMX 또는 많은 문자. 예를 들어, bl*
검정, 파랑 및 흐림 등을 구독합니다.
?
: 임의의 한 문자. 예를 들어, h?t
hit, hot and hat 등을 구독합니다.
[]
: 문자 범위. 예를 들어, b[ae]t
내기 및 배트를 구독하지만 비트는 구독하지 않습니다.
와일드카드로 구독 만들기
다음 예제에서는 패턴과 일치하여 주제가 구독되는 패턴을 제공하여 구독을 생성합니다.
// 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)
비동기 구독
배달 모드는 주문된 메시지에 대한 구독을 생성하는 동안 지정할 수 있으며 다음을 수행할 수 있습니다. sync
or async
. 다음 예에서는 다음을 사용하여 구독을 생성합니다. CreateSubscription
동기화 전달 모드가 있는 방법. 사용하는 것이 좋습니다 sync
주문된 메시지를 위한 모드 및 async
그렇지 않으면 고성능을 달성하기 위한 모드입니다.
구독을 생성하는 동안 동기 또는 비동기가 될 수 있는 배달 모드를 지정할 수 있습니다. 특히 동기 전달 모드를 사용할 수 있습니다. 주문된 메시지반면 정렬된 메시지를 사용하지 않는 경우 비동기 모드는 성능을 향상시킵니다.
주의 사항
기본적으로 메시지 배달 모드는 동기로 설정됩니다.
// 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")
추가 자료
NCache Pub/Sub용 샘플 애플리케이션 제공 GitHub의.
도 참조
.그물: Alachisoft.NCache.런타임.캐싱 네임 스페이스.
자바 : COM.alachisoft.ncache.런타임.캐싱 네임 스페이스.
Node.js : 주제구독 클래스 클래스입니다.
파이썬 : ncache.클라이언트.서비스 클래스입니다.