본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

Pub/sub

원문 보기 위키 갱신

이 문서는 프리뷰 기능에 대한 문서예요.

pub/sub 컴포넌트를 만드는 데는 몇 가지 기본 단계만 거치면 돼요.

출처: Dapr 문서

본문

pub/sub 네임스페이스 추가하기

pub/sub과 관련된 네임스페이스에 대한 using 문을 추가해요.

using Dapr.PluggableComponents.Components;
using Dapr.PluggableComponents.Components.PubSub;

IPubSub 구현하기

IPubSub 인터페이스를 구현하는 클래스를 만들어요.

internal sealed class MyPubSub : IPubSub
{
public Task InitAsync(MetadataRequest request, CancellationToken cancellationToken = default)
{
// Called to initialize the component with its configured metadata...
}

public Task PublishAsync(PubSubPublishRequest request, CancellationToken cancellationToken = default)
{
// Send the message to the "topic"...
}

public Task PullMessagesAsync(PubSubPullMessagesTopic topic, MessageDeliveryHandler<string?, PubSubPullMessagesResponse> deliveryHandler, CancellationToken cancellationToken = default)
{
// Until canceled, check the topic for messages and deliver them to the Dapr runtime...
}
}

PullMessagesAsync() 메서드에 대한 호출은 "수명이 긴(long-lived)" 호출이에요. 즉, 메서드는 취소될 때까지(예를 들어 cancellationToken을 통해) 반환되지 않을 거예요. 메시지를 가져올 "토픽(topic)"은 topic 인자를 통해 전달되고, Dapr 런타임으로의 전달은 deliveryHandler 콜백을 통해 수행돼요. 전달은 (Dapr 런타임이 제공하는) 애플리케이션이 메시지 처리를 확인(acknowledge)했을 때 컴포넌트가 알림을 받을 수 있게 해줘요.

public async Task PullMessagesAsync(PubSubPullMessagesTopic topic, MessageDeliveryHandler<string?, PubSubPullMessagesResponse> deliveryHandler, CancellationToken cancellationToken = default)
{
TimeSpan pollInterval = // Polling interval (e.g. from initalization metadata)...

// Poll the topic until canceled...
while (!cancellationToken.IsCancellationRequested)
{
var messages = // Poll topic for messages...

foreach (var message in messages)
{
// Deliver the message to the Dapr runtime...
await deliveryHandler(
new PubSubPullMessagesResponse(topicName)
{
// Set the message content...
},
// Callback invoked when application acknowledges the message...
async errorMessage =>
{
// An empty message indicates the application successfully processed the message...
if (String.IsNullOrEmpty(errorMessage))
{
// Delete the message from the topic...
}
})
}

// Wait for the next poll (or cancellation)...
await Task.Delay(pollInterval, cancellationToken);
}
}

pub/sub 컴포넌트 등록하기

메인 프로그램 파일(예: Program.cs)에서 애플리케이션 서비스에 pub/sub 컴포넌트를 등록해요.

using Dapr.PluggableComponents;

var app = DaprPluggableComponentsApplication.Create();

app.RegisterService(
"<socket name>",
serviceBuilder =>
{
serviceBuilder.RegisterPubSub<MyPubSub>();
});

app.Run();

다음 단계

  • 플러그형 컴포넌트 .NET SDK의 고급 단계 알아보기
  • 다음 용도로 플러그형 컴포넌트 .NET SDK를 사용하는 방법 알아보기:바인딩
  • 상태 저장소

더 알아보기 (Learn more)