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

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
举报
评论 0