Dapr’s gRPC Interface

Dapr and gRPC

Dapr implements both an HTTP and a gRPC API for local calls. gRPC is useful for low-latency, high performance scenarios and has language integration using the proto clients.

You can find a list of auto-generated clients .

The Dapr runtime implements a proto service that apps can communicate with via gRPC.

In addition to calling Dapr via gRPC, Dapr supports service to service calls with gRPC by acting as a proxy. See more information .

This tells Dapr to communicate with your app via gRPC over port 5005.

Kubernetes

On Kubernetes, set the following annotations in your deployment YAML:

  1. apiVersion: apps/v1
  2. kind: Deployment
  3. metadata:
  4. name: myapp
  5. namespace: default
  6. labels:
  7. app: myapp
  8. spec:
  9. replicas: 1
  10. selector:
  11. matchLabels:
  12. app: myapp
  13. template:
  14. metadata:
  15. labels:
  16. app: myapp
  17. annotations:
  18. dapr.io/enabled: "true"
  19. dapr.io/app-id: "myapp"
  20. dapr.io/app-protocol: "grpc"
  21. ...

The following steps show you how to create a Dapr client and call the SaveStateData operation on it:

  1. Import the package
  1. import (
  2. "context"
  3. "log"
  4. "os"
  5. dapr "github.com/dapr/go-sdk/client"
  6. )
  1. Create the client
  1. Invoke the Save State method
  1. // save state with the key key1
  2. err = client.SaveState(ctx, "statestore", "key1", data)
  3. if err != nil {
  4. log.Panic(err)
  5. }
  6. log.Println("data saved")

Hooray!

The following steps will show you how to create an app that exposes a server for Dapr to communicate with.

  1. Import the package
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "log"
  6. "net"
  7. "github.com/golang/protobuf/ptypes/empty"
  8. commonv1pb "github.com/dapr/go-sdk/dapr/proto/common/v1"
  9. pb "github.com/dapr/go-sdk/dapr/proto/runtime/v1"
  10. "google.golang.org/grpc"
  11. )
  1. Implement the interface
  1. Create the server
  1. func main() {
  2. // create listener
  3. lis, err := net.Listen("tcp", ":50001")
  4. if err != nil {
  5. log.Fatalf("failed to listen: %v", err)
  6. }
  7. // create grpc server
  8. s := grpc.NewServer()
  9. pb.RegisterAppCallbackServer(s, &server{})
  10. fmt.Println("Client starting...")
  11. // and start...
  12. if err := s.Serve(lis); err != nil {
  13. log.Fatalf("failed to serve: %v", err)
  14. }
  15. }

This creates a gRPC server for your app on port 4000.

  1. Run your app

To run locally, use the Dapr CLI:

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

On Kubernetes, set the required dapr.io/app-protocol: "grpc" and annotations in your pod spec template as mentioned above.