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 can communicate with an application via gRPC. To do that, the app needs to host a gRPC server and implements the
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.SaveStateData(ctx, "statestore", "key1", "1", data)
if err != nil {
logger.Panic(err)
}
logger.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.