健康检查用来检测 gRPC 服务是否可以处理 rpc 请求,gRPC 官方有专门的健康检查协议,官方也根据协议实现了相关的逻辑代码,gRPC 项目可以很方便得集成。接下来就讲解一下 gRPC 项目集成健康检查代码的方法。
gRPC 服务端
首先需要定义健康检查服务的名称,因为健康检查本身也是一个 gRPC 服务,一般情况下使用 grpc.health.v1.Health 即可:
const healthCheckService = "grpc.health.v1.Health"
然后需要导入以下几个关键的包
import (
"google.golang.org/grpc"
"google.golang.org/grpc/health"
healthpb "google.golang.org/grpc/health/grpc_health_v1"
)
注册健康检查服务
grpcServer := grpc.NewServer()
// 注册健康检查server
healthCheckServer := health.NewServer()
healthCheckServer.SetServingStatus(healthCheckService, healthpb.HealthCheckResponse_SERVING)
healthpb.RegisterHealthServer(grpcServer, healthCheckServer)
以上代码可以简写为一行
grpc_health_v1.RegisterHealthServer(grpcServer, health.NewServer())
以 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业务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 客户端
导入包
import(
"google.golang.org/grpc"
_ "google.golang.org/grpc/health"
)
grpc.Dial() 方法添加对应参数
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
如果是健康的服务,会有如下输出:
status: SERVING
如果服务挂掉了,会有如下输出:
timeout: failed to connect service "localhost:50051" within 1s
或者:
failed to connect service at "localhost:50051": context deadline exceeded
exit status