golang工程——grpc服务健康检查

多路复用与健康检查

参考grpc-health-probe 【grpc健康检查探针】

The grpc_health_probe utility allows you to query health of gRPC services that expose service their status through the gRPC Health Checking Protocol.

grpc_health_probe is meant to be used for health checking gRPC applications in Kubernetes, using the exec probes.

⚠️ Kubernetes v1.23 has now introduced built-in gRPC health checking capability as an alpha feature. As a result, you might no longer need to use this tool and use the native Kubernetes feature instead.

This tool can still be useful if you are on older versions of Kubernetes, or using advanced configuration (such as custom metadata, TLS or finer timeout tuning), or not using Kubernetes at all.

This command-line utility makes a RPC to /grpc.health.v1.Health/Check. If it responds with a SERVING status, the grpc_health_probe will exit with success, otherwise it will exit with a non-zero exit code (documented below).

EXAMPLES

$ grpc_health_probe -addr=localhost:5000
healthy: SERVING
$ grpc_health_probe -addr=localhost:9999 -connect-timeout 250ms -rpc-timeout 100ms
failed to connect service at "localhost:9999": context deadline exceeded
exit status 2

如果server启用tls,可以使用如下选项

If a gRPC server is serving traffic over TLS, or uses TLS client authentication to authorize clients, you can still use grpc_health_probe to check health with command-line options:

Option Description
-tls 启用tls
-tls-ca-cert 服务端根证书路径
-tls-client-cert 客户端证书
-tls-client-key 客户端私钥
-tls-no-verify 启用tls,但不需要验证证书(server使用INSECURE)
-tls-server-name 证书中服务名称

同时还提供了K8s中如何使用该组件 【https://github.com/grpc-ecosystem/grpc-health-probe】

以多路复用的方式进行健康检查

代码里需要将grpc服务器注册到健康检查服务中。

func main() {
    port = flag.Int("port", 50053, "port")
    flag.Parse()

    lis, err := net.Listen("tcp", fmt.Sprintf("localhost:%d", *port))

    if err != nil {
        log.Fatal(err)
    }

    // grpc server
    s := grpc.NewServer(getOptions()...)
    echo.RegisterEchoServer(s, &server.EchoServer{})
    log.Printf("server listening at : %v\n", lis.Addr())

    // 不需要把健康检查做成独立的服务,可以基于多路复用的机制 进行健康检查
    grpc_health_v1.RegisterHealthServer(s, health.NewServer())

    // 启动grpcserver
    go func() {
        if err := s.Serve(lis); err !=nil {
            log.Fatal(err)
        }
    }()
    ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, os.Kill)

    defer stop()

    <-ctx.Done()
}

启动后,调用健康检查的客户端(可执行文件)进行探测

D:\goProject\gobasic\grpc>grpc_health_probe-windows-amd64.exe  -tls -tls-ca-cert x509\ca_cert.pem -tls-client-cert x509\client_cert.pem -tls-client-key x509\client_key.pem -tls-server-name echo.grpc.0voice.com -addr localhost:50054
status: SERVING
# SERVING表示grpc服务正常

你可能感兴趣的:(golang,开发语言,后端)