선언적, 스트리밍, 프로그래매틱 구독 유형
메시지 토픽을 구독할 수 있게 해주는 구독 유형들에 대해 알아볼게요.
출처: Dapr 문서
본문
Pub/sub API 구독 유형
Dapr 애플리케이션은 같은 기능을 지원하는 세 가지 구독 유형(선언적, 스트리밍, 프로그래매틱)을 통해 게시된 토픽을 구독할 수 있어요.
| 구독 유형 | 설명 | | Declarative (선언적) | 구독이 외부 파일에 정의돼요. 선언적 방식은 코드에서 Dapr 의존성을 제거하고, 기존 애플리케이션이 코드를 바꾸지 않고 토픽을 구독할 수 있게 해줘요. | | Streaming (스트리밍) | 구독이 애플리케이션 코드에 정의돼요. 스트리밍 구독은 동적이라서 실행 중에도 구독을 추가하거나 제거할 수 있어요. 애플리케이션에 구독 엔드포인트가 필요 없어서(프로그래매틱·선언적 구독은 모두 필요해요) 코드에서 설정하기 쉬워요. 스트리밍 구독은 사이드카로 메시지를 받도록 앱을 설정할 필요도 없어요. | | Programmatic (프로그래매틱) | 구독이 애플리케이션 코드에 정의돼요. 프로그래매틱 방식은 정적 구독을 구현하며 코드에 엔드포인트가 필요해요. |
아래 예시들은 checkout 앱과 orderprocessing 앱 사이에서 orders 토픽을 통해 pub/sub 메시징을 하는 모습을 보여줘요. 같은 Dapr pub/sub 컴포넌트를 먼저 선언적으로, 그다음 프로그래매틱하게 사용하는 예시예요.
선언적 구독
참고
선언적 구독은 기본적으로 "핫 리로드(hot reload)"돼요. 즉 재시작 없이도 업데이트가 자동으로 반영돼요. 이 기능을 끄려면 Dapr 애플리케이션 구성에서 HotReload 기능을 비활성화해요.
spec:
features:
- name: HotReload
enabled: false
핫 리로드 이벤트 중에는 미처리 메시지의 재처리나 손실을 막기 위해, Dapr과 애플리케이션 사이의 진행 중(in-flight) 메시지는 영향을 받지 않아요.
외부 컴포넌트 파일을 사용해 선언적으로 토픽을 구독할 수 있어요. 이 예시는 subscription.yaml이라는 이름의 YAML 컴포넌트 파일을 사용해요.
apiVersion: dapr.io/v2alpha1
kind: Subscription
metadata:
name: order
spec:
topic: orders
routes:
default: /orders
pubsubname: pubsub
scopes:
- orderprocessing
여기서 order라는 이름의 구독은:
pubsub라는 이름의 pub/sub 컴포넌트를 사용해orders라는 토픽을 구독해요.- route 필드를 설정해 모든 토픽 메시지를 앱의 /orders 엔드포인트로 보내요.
- scopes 필드를 설정해 이 구독을 ID가
orderprocessing인 앱만 접근할 수 있게 범위를 지정해요.
Dapr을 실행할 때는 YAML 컴포넌트 파일 경로를 설정해 Dapr이 그 컴포넌트를 가리키도록 해요.
- .NET
- Java
- Python
- JavaScript
- Go
- Kubernetes
dapr run --app-id myapp --resources-path ./myComponents -- dotnet run
dapr run --app-id myapp --resources-path ./myComponents -- mvn spring-boot:run
dapr run --app-id myapp --resources-path ./myComponents -- python3 app.py
dapr run --app-id myapp --resources-path ./myComponents -- npm start
dapr run --app-id myapp --resources-path ./myComponents -- go run app.go
Kubernetes에서는 컴포넌트를 클러스터에 적용해요.
kubectl apply -f subscription.yaml
애플리케이션 코드에서는 Dapr pub/sub 컴포넌트에 지정된 토픽을 구독해요.
- .NET
- Java
- Python
- JavaScript
- Go
//Subscribe to a topic
[HttpPost("orders")]
public void getCheckout([FromBody] int orderId)
{
Console.WriteLine("Subscriber received : " + orderId);
}
import io.dapr.client.domain.CloudEvent;
//Subscribe to a topic
@PostMapping(path = "/orders")
public Mono<Void> getCheckout(@RequestBody(required = false) CloudEvent<String> cloudEvent) {
return Mono.fromRunnable(() -> {
try {
log.info("Subscriber received: " + cloudEvent.getData());
}
});
}
from cloudevents.sdk.event import v1
#Subscribe to a topic
@app.route('/orders', methods=['POST'])
def checkout(event: v1.Event) -> None:
data = json.loads(event.Data())
logging.info('Subscriber received: ' + str(data))
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
app.use(bodyParser.json({ type: 'application/*+json' }));
// listen to the declarative route
app.post('/orders', (req, res) => {
console.log(req.body);
res.sendStatus(200);
});
//Subscribe to a topic
var sub = &common.Subscription{
PubsubName: "pubsub",
Topic: "orders",
Route: "/orders",
}
func eventHandler(ctx context.Context, e *common.TopicEvent) (retry bool, err error) {
log.Printf("Subscriber received: %s", e.Data)
return false, nil
}
/orders 엔드포인트는 구독에 정의된 route와 일치해요. Dapr이 모든 토픽 메시지를 보내는 곳이 바로 이 엔드포인트예요.
스트리밍 구독
스트리밍 구독은 애플리케이션 코드에 정의되며 실행 중에 동적으로 시작하고 중지할 수 있는 구독이에요. 메시지는 애플리케이션이 Dapr에서 직접 가져와요(pull). 즉 토픽을 구독하는 데 엔드포인트가 필요 없고, 사이드카에 앱을 전혀 구성하지 않고도 구독할 수 있어요. 원하는 만큼 많은 pubsub과 토픽을 한 번에 구독할 수 있어요.
메시지는 주어진 메시지 핸들러 코드로 보내지기 때문에 라우트나 벌크 구독의 개념이 없어요. 아래 예시는 토픽을 스트리밍 구독하는 여러 방법을 보여줘요.
- .NET
- Python
- Go
DaprPublishSubscribeClient의 SubscribeAsync 메서드를 사용해 스트림에서 메시지를 가져오는 메시지 핸들러를 구성할 수 있어요.
using System.Text;
using Dapr.Messaging;
using Dapr.Messaging.PublishSubscribe;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDaprMessaging()
.AddDaprPubSub();
var app = builder.Build();
var messagingClient = app.Services.GetRequiredService<DaprPublishSubscribeClient>();
// Create a dynamic streaming subscription and subscribe with a timeout of 30 seconds and 10 seconds for message handling
var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(30));
var subscription = await messagingClient.SubscribeAsync("pubsub", "myTopic",
new DaprSubscriptionOptions(new MessageHandlingPolicy(TimeSpan.FromSeconds(10), TopicResponseAction.Retry)),
HandleMessageAsync, cancellationTokenSource.Token);
await Task.Delay(TimeSpan.FromMinutes(1));
// When you're done with the subscription, dispose of it to cleanly stop receiving events
await subscription.DisposeAsync();
return;
// Process each message returned from the subscription
Task<TopicResponseAction> HandleMessageAsync(TopicMessage message, CancellationToken cancellationToken = default)
{
try
{
// Do something with the message
Console.WriteLine(Encoding.UTF8.GetString(message.Data.Span));
return Task.FromResult(TopicResponseAction.Success);
}
catch
{
return Task.FromResult(TopicResponseAction.Retry);
}
}
.NET SDK를 사용한 pub/sub 구독에 대해 더 알아보세요.
subscribe 메서드를 사용할 수도 있어요. 이 메서드는 Subscription 객체를 반환하고, next_message 메서드를 호출해 스트림에서 메시지를 가져올 수 있어요. 이 방식은 main 스레드에서 실행되며 메시지를 기다리는 동안 블로킹될 수 있어요.
import time
from dapr.clients import DaprClient
from dapr.clients.grpc.subscription import StreamInactiveError
counter = 0
def process_message(message):
global counter
counter += 1
print(f'Processing message: {message.data()} from {message.topic()}...')
return 'success'
def main():
with DaprClient() as client:
global counter
subscription = client.subscribe(
pubsub_name='pubsub', topic='orders', dead_letter_topic='orders_dead'
)
try:
while counter < 5:
try:
message = subscription.next_message()
except StreamInactiveError as e:
print('Stream is inactive. Retrying...')
time.sleep(1)
continue
if message is None:
print('No message received within timeout period.')
continue
response_status = process_message(message)
if response_status == 'success':
subscription.respond_success(message)
elif response_status == 'retry':
subscription.respond_retry(message)
elif response_status == 'drop':
subscription.respond_drop(message)
finally:
print("Closing subscription...")
subscription.close()
if __name__ == '__main__':
main()
subscribe_with_handler 메서드도 사용할 수 있어요. 이 메서드는 스트림에서 받은 각 메시지에 대해 실행되는 콜백 함수를 받아요. 이 방식은 별도 스레드에서 실행되므로 main 스레드를 블로킹하지 않아요.
import time
from dapr.clients import DaprClient
from dapr.clients.grpc._response import TopicEventResponse
counter = 0
def process_message(message):
global counter
counter += 1
print(f'Processing message: {message.data()} from {message.topic()}...')
return TopicEventResponse('success')
def main():
with (DaprClient() as client):
close_fn = client.subscribe_with_handler(
pubsub_name='pubsub', topic='orders', handler_fn=process_message,
dead_letter_topic='orders_dead'
)
while counter < 5:
time.sleep(1)
print("Closing subscription...")
close_fn()
if __name__ == '__main__':
main()
Python SDK 클라이언트를 사용한 스트리밍 구독에 대해 더 알아보세요.
package main
import (
"context"
"log"
"github.com/dapr/go-sdk/client"
)
func main() {
cl, err := client.NewClient()
if err != nil {
log.Fatal(err)
}
sub, err := cl.Subscribe(context.Background(), client.SubscriptionOptions{
PubsubName: "pubsub",
Topic: "orders",
})
if err != nil {
panic(err)
}
// Close must always be called.
defer sub.Close()
for {
msg, err := sub.Receive()
if err != nil {
panic(err)
}
// Process the event
// We _MUST_ always signal the result of processing the message, else the
// message will not be considered as processed and will be redelivered or
// dead lettered.
// msg.Retry()
// msg.Drop()
if err := msg.Success(); err != nil {
panic(err)
}
}
}
또는
package main
import (
"context"
"log"
"github.com/dapr/go-sdk/client"
"github.com/dapr/go-sdk/service/common"
)
func main() {
cl, err := client.NewClient()
if err != nil {
log.Fatal(err)
}
stop, err := cl.SubscribeWithHandler(context.Background(),
client.SubscriptionOptions{
PubsubName: "pubsub",
Topic: "orders",
},
eventHandler,
)
if err != nil {
panic(err)
}
// Stop must always be called.
defer stop()
<-make(chan struct{})
}
func eventHandler(e *common.TopicEvent) common.SubscriptionResponseStatus {
// Process message here
// common.SubscriptionResponseStatusRetry
// common.SubscriptionResponseStatusDrop
common.SubscriptionResponseStatusDrop, status)
}
return common.SubscriptionResponseStatusSuccess
}
데모
이 동영상에서 스트리밍 구독 개요를 확인해 보세요.
프로그래매틱 구독
동적 프로그래매틱 방식은 선언적 방식의 route YAML 구조와는 달리 코드 안에서 routes JSON 구조를 반환해요.
참고: 프로그래매틱 구독은 애플리케이션 시작 시 한 번만 읽혀요. 프로그래매틱 구독을 동적으로 새로 추가할 수는 없고, 컴파일 시점에만 새로 추가할 수 있어요.
프로그래매틱 구독 비활성화
애플리케이션이 프로그래매틱 구독을 사용하지 않는다면, /dapr/subscribe에 대한 자동 HTTP 호출을 비활성화해 로그 노이즈를 줄일 수 있어요. dapr run과 함께 --disable-init-endpoints subscribe 플래그를 사용하거나, Kubernetes에서 dapr.io/disable-init-endpoints: "subscribe" 어노테이션을 사용해요. 초기화 엔드포인트 비활성화에 대해 더 알아보세요.
아래 예시에서는 위의 선언적 YAML 구독에서 찾을 수 있는 값들을 애플리케이션 코드 안에서 정의해요.
- .NET
- Java
- Python
- JavaScript
- Go
[Topic("pubsub", "orders")]
[HttpPost("/orders")]
public async Task<ActionResult<Order>>Checkout(Order order, [FromServices] DaprClient daprClient)
{
// Logic
return order;
}
또는
// Dapr subscription in [Topic] routes orders topic to this route
app.MapPost("/orders", [Topic("pubsub", "orders")] (Order order) => {
Console.WriteLine("Subscriber received : " + order);
return Results.Ok(order);
});
위에서 정의한 두 핸들러 모두 dapr/subscribe 엔드포인트를 구성하도록 매핑되어야 해요. 이 작업은 엔드포인트를 정의하는 애플리케이션 시작 코드에서 수행돼요.
app.UseEndpoints(endpoints =>
{
endpoints.MapSubscribeHandler();
});
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
@Topic(name = "orders", pubsubName = "pubsub")
@PostMapping(path = "/orders")
public Mono<Void> handleMessage(@RequestBody(required = false) CloudEvent<String> cloudEvent) {
return Mono.fromRunnable(() -> {
try {
System.out.println("Subscriber received: " + cloudEvent.getData());
System.out.println("Subscriber received: " + OBJECT_MAPPER.writeValueAsString(cloudEvent));
} catch (Exception e) {
throw new RuntimeException(e);
}
});
}
@app.route('/dapr/subscribe', methods=['GET'])
def subscribe():
subscriptions = [
{
'pubsubname': 'pubsub',
'topic': 'orders',
'routes': {
'rules': [
{
'match': 'event.type == "order"',
'path': '/orders'
},
],
'default': '/orders'
}
}]
return jsonify(subscriptions)
@app.route('/orders', methods=['POST'])
def ds_subscriber():
print(request.json, flush=True)
return json.dumps({'success':True}), 200, {'ContentType':'application/json'}
app.run()
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
app.use(bodyParser.json({ type: 'application/*+json' }));
const port = 3000
app.get('/dapr/subscribe', (req, res) => {
res.json([
{
pubsubname: "pubsub",
topic: "orders",
routes: {
rules: [
{
match: 'event.type == "order"',
path: '/orders'
},
],
default: '/products'
}
}
]);
})
app.post('/orders', (req, res) => {
console.log(req.body);
res.sendStatus(200);
});
app.listen(port, () => console.log(`consumer app listening on port ${port}!`))
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"github.com/gorilla/mux"
)
const appPort = 3000
type subscription struct {
PubsubName string `json:"pubsubname"`
Topic string `json:"topic"`
Metadata map[string]string `json:"metadata,omitempty"`
Routes routes `json:"routes"`
}
type routes struct {
Rules []rule `json:"rules,omitempty"`
Default string `json:"default,omitempty"`
}
type rule struct {
Match string `json:"match"`
Path string `json:"path"`
}
// This handles /dapr/subscribe
func configureSubscribeHandler(w http.ResponseWriter, _ *http.Request) {
t := []subscription{
{
PubsubName: "pubsub",
Topic: "orders",
Routes: routes{
Rules: []rule{
{
Match: `event.type == "order"`,
Path: "/orders",
},
},
Default: "/orders",
},
},
}
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(t)
}
func main() {
router := mux.NewRouter().StrictSlash(true)
router.HandleFunc("/dapr/subscribe", configureSubscribeHandler).Methods("GET")
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", appPort), router))
}
로컬에서 구독 확인하기
어떤 구독 유형을 선택하든, 로컬 개발 중에 Dapr Dev Dashboard를 사용해 각 앱이 등록한 구독(pub/sub 컴포넌트, 토픽, 라우트 포함)을 확인할 수 있어요. 선언적 구독 파일이 로드됐는지, 앱이 기대한 프로그래매틱 구독을 반환했는지 빠르게 확인하기 좋아요. 대시보드에서 구독에 테스트 메시지를 보낼 수도 있어요.
다음 단계
- pub/sub 퀵스타트를 시도해 봐요.
- How-To: 여러 네임스페이스로 pub/sub 컴포넌트 구성하기를 따라 해 봐요.
- 선언적·프로그래매틱 구독 방법에 대해 더 알아봐요.
- 토픽 범위 지정에 대해 알아봐요.
- 메시지 TTL에 대해 알아봐요.
- CloudEvent 사용 여부에 따른 pub/sub에 대해 더 알아봐요.
- pub/sub 컴포넌트 목록을 확인해요.
- pub/sub API 레퍼런스를 읽어봐요.