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

Pub/sub

원문 보기 위키 갱신

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

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

출처: Dapr 문서

본문

pub/sub 패키지 가져오기

components/pubsub.go 파일을 만들고 pub/sub 관련 패키지에 대한 import 문을 추가해요.

package components

import (
"context"
"github.com/dapr/components-contrib/pubsub"
)

PubSub 인터페이스 구현하기

PubSub 인터페이스를 구현하는 타입을 만들어요.

type MyPubSubComponent struct {
}

func (component *MyPubSubComponent) Init(metadata pubsub.Metadata) error {
// Called to initialize the component with its configured metadata...
}

func (component *MyPubSubComponent) Close() error {
// Not used with pluggable components...
return nil
}

func (component *MyPubSubComponent) Features() []pubsub.Feature {
// Return a list of features supported by the component...
}

func (component *MyPubSubComponent) Publish(req *pubsub.PublishRequest) error {
// Send the message to the "topic"...
}

func (component *MyPubSubComponent) Subscribe(ctx context.Context, req pubsub.SubscribeRequest, handler pubsub.Handler) error {
// Until canceled, check the topic for messages and deliver them to the Dapr runtime...
}

Subscribe() 메서드에 대한 호출은 메시지를 가져오는 수명이 긴(long-lived) 메커니즘을 설정하되 즉시 nil(또는 그 메커니즘을 설정할 수 없다면 오류)을 반환할 것으로 기대돼요. 그 메커니즘은 취소될 때(예를 들어 ctx.Done() 또는 ctx.Err() != nil을 통해) 종료되어야 해요. 메시지를 가져올 "토픽(topic)"은 req 인자를 통해 전달되고, Dapr 런타임으로의 전달은 handler 콜백을 통해 수행돼요. 이 콜백은 (Dapr 런타임이 제공하는) 애플리케이션이 메시지 처리를 확인(acknowledge)할 때까지 반환되지 않아요.

func (component *MyPubSubComponent) Subscribe(ctx context.Context, req pubsub.SubscribeRequest, handler pubsub.Handler) error {
go func() {
for {
err := ctx.Err()

if err != nil {
return
}

messages := // Poll for messages...

for _, message := range messages {
handler(ctx, &pubsub.NewMessage{
// Set the message content...
})
}

select {
case <-ctx.Done():
case <-time.After(5 * time.Second):
}
}
}()

return nil
}

pub/sub 컴포넌트 등록하기

메인 애플리케이션 파일(예: main.go)에서 애플리케이션에 pub/sub 컴포넌트를 등록해요.

package main

import (
"example/components"
dapr "github.com/dapr-sandbox/components-go-sdk"
"github.com/dapr-sandbox/components-go-sdk/pubsub/v1"
)

func main() {
dapr.Register("<socket name>", dapr.WithPubSub(func() pubsub.PubSub {
return &components.MyPubSubComponent{}
}))

dapr.MustRun()
}

다음 단계

  • 플러그형 컴포넌트 Go SDK의 고급 기법
  • 다음 구현 방법 더 알아보기:바인딩
  • 상태

더 알아보기 (Learn more)