
gRPC服務(wù)健康檢查(Health Checking)
健康檢查用來(lái)檢測(cè)gRPC服務(wù)是否可以處理rpc請(qǐng)求,gRPC官方有專門的健康檢查協(xié)議,官方也根據(jù)協(xié)議實(shí)現(xiàn)了相關(guān)的邏輯代碼,gRPC項(xiàng)目可以很方便得集成。接下來(lái)就講解一下gRPC項(xiàng)目集成健康檢查代碼的方法。
gRPC服務(wù)集成健康檢查代碼的方法
首先需要定義健康檢查服務(wù)的名稱,因?yàn)榻】禉z查本身也是一個(gè)gRPC服務(wù),一般情況下使用grpc.health.v1.Health即可:
const healthCheckService = "grpc.health.v1.Health"
然后需要導(dǎo)入以下幾個(gè)關(guān)鍵的包:
import (
"google.golang.org/grpc"
"google.golang.org/grpc/health"
healthpb "google.golang.org/grpc/health/grpc_health_v1"
)
注冊(cè)健康檢查服務(wù):
s := grpc.NewServer()
// 注冊(cè)健康檢查server
healthCheckServer := health.NewServer()
healthCheckServer.SetServingStatus(healthCheckService, healthpb.HealthCheckResponse_SERVING)
healthpb.RegisterHealthServer(s, healthCheckServer)
這樣就完成集成工作了,很簡(jiǎn)單吧?
完整代碼如下,以gRPC官方的helloworld服務(wù)為例(下面的代碼可以直接運(yùn)行):
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è)務(wù)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客戶端集成健康檢查代碼
需要導(dǎo)入以下幾個(gè)關(guān)鍵的包:
import(
"google.golang.org/grpc"
_ "google.golang.org/grpc/health"
)
grpc.Dial() 方法添加對(duì)應(yīng)參數(shù):
conn, err := grpc.Dial(
*addr,
grpc.WithTransportCredentials(insecure.NewCredentials()),
grpc.WithDefaultServiceConfig(fmt.Sprintf(`{"HealthCheckConfig": {"ServiceName": "%s"}}`, healthCheckService)),
)
完整代碼如下,以gRPC官方的helloworld為例(下面的代碼可以直接運(yùn)行):
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工具進(jìn)行健康檢查
安裝grpc-health-probe:
go install github.com/grpc-ecosystem/grpc-health-probe@latest
安裝完成后,對(duì)上面的gRPC服務(wù)進(jìn)行健康檢查:
grpc-health-probe -addr=localhost:50051
如果是健康的服務(wù),會(huì)有如下輸出:
如果服務(wù)掛掉了,會(huì)有如下輸出:
timeout: failed to connect service "localhost:50051" within 1s
或者:
failed to connect service at "localhost:50051": context deadline exceeded
exit status 2