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

방법: Dapr 애플리케이션에서 gRPC 인터페이스 사용하기

원문 보기 위키 갱신

애플리케이션에서 Dapr gRPC API를 사용하는 방법을 안내해요. Dapr은 로컬 호출을 위해 HTTP API와 gRPC API를 모두 구현해요. gRPC는 저지연·고성능 시나리오에 유용하며 proto 클라이언트를 이용한 언어 통합을 제공해요. 자동 생성된 클라이언트 목록은 Dapr SDK 문서에서 찾을 수 있어요. Dapr 런타임은 앱이 gRPC로 통신할 수 있는 proto 서비스를 구현해요. gRPC로 Dapr을 호출하는 것 외에도, Dapr은 프록시 역할을 하며 gRPC로 서비스 간 호출(service-to-service)을 지원해요. 자세한 내용은 gRPC 서비스 호출 방법 가이드에서 확인할 수 있어요. 이 가이드는 Go SDK 애플리케이션을 사용해 Dapr을 gRPC로 구성하고 호출하는 방법을 보여줘요.

출처: Dapr 문서

본문

Dapr이 gRPC로 앱과 통신하도록 구성

  • 자체 호스팅
  • Kubernetes

자체 호스팅 모드로 실행할 때는 --app-protocol 플래그를 사용해 Dapr이 앱과 통신할 때 gRPC를 사용하도록 지정해요.

dapr run --app-protocol grpc --app-port 5005 node app.js

이렇게 하면 Dapr이 포트 5005에서 gRPC로 앱과 통신하도록 지정돼요.

Kubernetes에서는 배포 YAML에 다음 어노테이션을 설정해요.

apiVersion: apps/v1
kind: Deployment
metadata:
name: myapp
namespace: default
labels:
app: myapp
spec:
replicas: 1
selector:
matchLabels:
app: myapp
template:
metadata:
labels:
app: myapp
annotations:
dapr.io/enabled: "true"
dapr.io/app-id: "myapp"
dapr.io/app-protocol: "grpc"
dapr.io/app-port: "5005"
...

gRPC로 Dapr 호출

다음 단계는 Dapr 클라이언트를 만들고 그에 대해 SaveStateData 연산을 호출하는 방법을 보여줘요.

  • 패키지 가져오기:
package main

import (
"context"
"log"
"os"

dapr "github.com/dapr/go-sdk/client"
)
  • 클라이언트 만들기:
// just for this demo
ctx := context.Background()
data := []byte("ping")

// create the client
client, err := dapr.NewClient()
if err != nil {
log.Panic(err)
}
defer client.Close()

SaveState 메서드를 호출해요.

// save state with the key key1
err = client.SaveState(ctx, "statestore", "key1", data)
if err != nil {
log.Panic(err)
}
log.Println("data saved")

이제 Dapr 클라이언트의 다양한 메서드를 모두 살펴볼 수 있어요.

Dapr로 gRPC 앱 만들기

다음 단계는 Dapr이 통신할 서버를 노출하는 앱을 만드는 방법을 보여줘요.

  • 패키지 가져오기:
package main

import (
"context"
"fmt"
"log"
"net"

"github.com/golang/protobuf/ptypes/any"
"github.com/golang/protobuf/ptypes/empty"

commonv1pb "github.com/dapr/dapr/pkg/proto/common/v1"
pb "github.com/dapr/dapr/pkg/proto/runtime/v1"
"google.golang.org/grpc"
)
  • 인터페이스 구현하기:
// server is our user app
type server struct {
pb.UnimplementedAppCallbackServer
}

// EchoMethod is a simple demo method to invoke
func (s *server) EchoMethod() string {
return "pong"
}

// This method gets invoked when a remote service has called the app through Dapr
// The payload carries a Method to identify the method, a set of metadata properties and an optional payload
func (s *server) OnInvoke(ctx context.Context, in *commonv1pb.InvokeRequest) (*commonv1pb.InvokeResponse, error) {
var response string

switch in.Method {
case "EchoMethod":
response = s.EchoMethod()
}

return &commonv1pb.InvokeResponse{
ContentType: "text/plain; charset=UTF-8",
Data: &any.Any{Value: []byte(response)},
}, nil
}

// Dapr will call this method to get the list of topics the app wants to subscribe to. In this example, we are telling Dapr
// To subscribe to a topic named TopicA
func (s *server) ListTopicSubscriptions(ctx context.Context, in *empty.Empty) (*pb.ListTopicSubscriptionsResponse, error) {
return &pb.ListTopicSubscriptionsResponse{
Subscriptions: []*pb.TopicSubscription{
{Topic: "TopicA"},
},
}, nil
}

// Dapr will call this method to get the list of bindings the app will get invoked by. In this example, we are telling Dapr
// To invoke our app with a binding named storage
func (s *server) ListInputBindings(ctx context.Context, in *empty.Empty) (*pb.ListInputBindingsResponse, error) {
return &pb.ListInputBindingsResponse{
Bindings: []string{"storage"},
}, nil
}

// This method gets invoked every time a new event is fired from a registered binding. The message carries the binding name, a payload and optional metadata
func (s *server) OnBindingEvent(ctx context.Context, in *pb.BindingEventRequest) (*pb.BindingEventResponse, error) {
fmt.Println("Invoked from binding")
return &pb.BindingEventResponse{}, nil
}

// This method is fired whenever a message has been published to a topic that has been subscribed. Dapr sends published messages in a CloudEvents 0.3 envelope.
func (s *server) OnTopicEvent(ctx context.Context, in *pb.TopicEventRequest) (*pb.TopicEventResponse, error) {
fmt.Println("Topic message arrived")
return &pb.TopicEventResponse{}, nil
}
  • 서버 만들기:
func main() {
// create listener
lis, err := net.Listen("tcp", ":50001")
if err != nil {
log.Fatalf("failed to listen: %v", err)
}

// create grpc server
s := grpc.NewServer()
pb.RegisterAppCallbackServer(s, &server{})

fmt.Println("Client starting...")

// and start...
if err := s.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}

이렇게 하면 포트 50001에서 앱용 gRPC 서버가 만들어져요.

애플리케이션 실행

  • 자체 호스팅
  • Kubernetes

로컬에서 실행하려면 Dapr CLI를 사용해요.

dapr run --app-id goapp --app-port 50001 --app-protocol grpc go run main.go

Kubernetes에서는 위에서 언급한 대로 파드 스펙 템플릿에 dapr.io/app-protocol: "grpc" 및 dapr.io/app-port: "50001" 어노테이션을 설정해요.

다른 언어

Protobuf가 지원하는 모든 언어로 Dapr을 사용할 수 있으며, 현재 사용 가능한 생성 SDK뿐만 아니라 사용할 수 있어요. protoc 도구를 사용하면 Ruby, C++, Rust 등 다른 언어용 Dapr 클라이언트를 생성할 수 있어요.

관련 주제

  • 서비스 호출 빌딩 블록
  • 서비스 호출 API 명세

더 알아보기 (Learn more)