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:
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"
...
The following steps show you how to create a Dapr client and call the SaveStateData
operation on it:
- Import the package
import (
"context"
"log"
"os"
dapr "github.com/dapr/go-sdk/client"
)
- Create the client
- Invoke the Save State method
// save state with the key key1
err = client.SaveState(ctx, "statestore", "key1", data)
if err != nil {
log.Panic(err)
}
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.
- Import the package
package main
import (
"context"
"fmt"
"log"
"net"
"github.com/golang/protobuf/ptypes/empty"
commonv1pb "github.com/dapr/go-sdk/dapr/proto/common/v1"
pb "github.com/dapr/go-sdk/dapr/proto/runtime/v1"
"google.golang.org/grpc"
)
- Implement the interface
- Create the server
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)
}
}
This creates a gRPC server for your app on port 4000.
- Run your app
To run locally, use the Dapr CLI:
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.