
gRPC服務健康檢查(Health Checking)
健康檢查用來檢測gRPC服務是否可以處理rpc請求,gRPC官方有專門的健康檢查協(xié)議,官方也根據(jù)協(xié)議實現(xiàn)了相關(guān)的邏輯代碼,gRPC項目可以很方便得集成。接下來就講解一下gRPC項目集成健康檢查代碼的方法。
gRPC服務集成健康檢查代碼的方法
首先需要定義健康檢查服務的名稱,因為健康檢查本身也是一個gRPC服務,一般情況下使用grpc.health.v1.Health即可:
const healthCheckService = "grpc.health.v1.Health"
然后需要導入以下幾個關(guān)鍵的包:
import (
"google.golang.org/grpc"
"google.golang.org/grpc/health"
healthpb "google.golang.org/grpc/health/grpc_health_v1"
)
注冊健康檢查服務:
s := grpc.NewServer()
// 注冊健康檢查server
healthCheckServer := health.NewServer()
healthCheckServer.SetServingStatus(healthCheckService, healthpb.HealthCheckResponse_SERVING)
healthpb.RegisterHealthServer(s, healthCheckServer)
這樣就完成集成工作了,很簡單吧?
完整代碼如下,以gRPC官方的helloworld服務為例(下面的代碼可以直接運行):
package main
import (
"context"
"flag"
"fmt"
"log"
"net"
"google.golang.org/grpc"
pb "google.golang.org/grpc/examples/helloworld/helloworld"
"google.golang.org/grpc/health"
healthpb "google.golang.org/grpc/health/grpc_health_v1"
)
var (
port = flag.Int("port", 50051, "The server port")
)
const healthCheckService = "grpc.health.v1.Health"
// server is used to implement helloworld.GreeterServer.
type server struct {
pb.UnimplementedGreeterServer
}
// SayHello implements helloworld.GreeterServer
func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
log.Printf("Received: %v", in.GetName())
return &pb.HelloReply{Message: "Hello " + in.GetName()}, nil
}
func main() {
flag.Parse()
lis, err := net.Listen("tcp", fmt.Sprintf(":%d", *port))
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
s := grpc.NewServer()
// register業(yè)務server
pb.RegisterGreeterServer(s, &server{})
// register健康檢查server
// health check server
healthCheckServer := health.NewServer()
healthCheckServer.SetServingStatus(healthCheckService, healthpb.HealthCheckResponse_SERVING)
healthpb.RegisterHealthServer(s, healthCheckServer)
log.Printf("server listening at %v", lis.Addr())
if err := s.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}
gRPC客戶端集成健康檢查代碼
需要導入以下幾個關(guān)鍵的包:
import(
"google.golang.org/grpc"
_ "google.golang.org/grpc/health"
)
grpc.Dial() 方法添加對應參數(shù):
conn, err := grpc.Dial(
*addr,
grpc.WithTransportCredentials(insecure.NewCredentials()),
grpc.WithDefaultServiceConfig(fmt.Sprintf(`{"HealthCheckConfig": {"ServiceName": "%s"}}`, healthCheckService)),
)
完整代碼如下,以gRPC官方的helloworld為例(下面的代碼可以直接運行):
package main
import (
"context"
"flag"
"fmt"
"log"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
pb "google.golang.org/grpc/examples/helloworld/helloworld"
_ "google.golang.org/grpc/health"
)
const (
defaultName = "world"
healthCheckService = "grpc.health.v1.Health"
)
var (
addr = flag.String("addr", "localhost:50051", "the address to connect to")
name = flag.String("name", defaultName, "Name to greet")
)
func main() {
flag.Parse()
// Set up a connection to the server.
conn, err := grpc.Dial(
*addr,
grpc.WithTransportCredentials(insecure.NewCredentials()),
grpc.WithDefaultServiceConfig(fmt.Sprintf(`{"HealthCheckConfig": {"ServiceName": "%s"}}`, healthCheckService)),
)
if err != nil {
log.Fatalf("did not connect: %v", err)
}
defer conn.Close()
c := pb.NewGreeterClient(conn)
// Contact the server and print out its response.
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
r, err := c.SayHello(ctx, &pb.HelloRequest{Name: *name})
if err != nil {
log.Fatalf("could not greet: %v", err)
}
log.Printf("Greeting: %s", r.GetMessage())
}
使用grpc-health-probe工具進行健康檢查
安裝grpc-health-probe:
go install github.com/grpc-ecosystem/grpc-health-probe@latest
安裝完成后,對上面的gRPC服務進行健康檢查:
grpc-health-probe -addr=localhost:50051
如果是健康的服務,會有如下輸出:
如果服務掛掉了,會有如下輸出:
timeout: failed to connect service "localhost:50051" within 1s
或者:
failed to connect service at "localhost:50051": context deadline exceeded
exit status 2