gRPC服务健康检查(一):Golang项目集成服务健康检查代码

开发 架构
本篇给大家讲解一下gRPC项目集成健康检查代码的方法。

gRPC服务健康检查(Health Checking)

健康检查用来检测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"
)

注册健康检查服务:

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业务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 2
责任编辑:姜华 来源: 今日头条
相关推荐

2023-03-02 07:20:10

GRPC服务健康检查协议

2023-03-03 08:19:35

KubernetesgRPC

2017-08-25 10:20:46

Docker容器机制

2021-07-15 10:25:15

集群节点检查

2020-12-07 06:29:13

SpringBoot

2023-05-09 07:34:25

Docker健康检查方式

2023-10-14 15:36:14

PodKubernetes

2024-02-27 17:30:11

2021-07-05 06:51:41

Nacos微服务源码

2022-09-07 09:19:49

Docker健康检查

2021-09-18 16:10:48

Spring BootJava微服务

2021-04-18 10:34:28

Spring Clou邮件钉钉

2021-01-15 05:38:28

ASPHttp端口

2022-02-28 07:40:23

Nacos注册中心客户端

2023-03-07 07:49:06

Kubernetes容器

2021-09-21 16:31:56

Windows 11微软PC健康检查工具

2024-10-31 15:16:35

2024-09-04 10:44:19

2022-07-08 08:37:23

Nacos服务注册动态配置

2021-09-22 23:08:50

Windows 11Windows微软
点赞
收藏

51CTO技术栈公众号