consul的grpc健康检查

开始使用go-kit进行开发接口,我都会写一个health接口,用于consul的健康检查。
其实开始也想过,如果每一个人都对健康检查接口开发出一个不同的请求体,如果这样,consul怎样对health的接口进行调用呢,但是当时只是一闪而过的想法,并没有想太多,直到我看到注册的服务报红我才意识到,健康检查的接口不应该这么写。
这次我们进行健康检查的接口开发。
首先,我们需要实现consul封装的特定的接口

type HealthServer interface {
	// If the requested service is unknown, the call will fail with status
	// NOT_FOUND.
	Check(context.Context, *HealthCheckRequest) (*HealthCheckResponse, error)
	// Performs a watch for the serving status of the requested service.
	// The server will immediately send back a message indicating the current
	// serving status.  It will then subsequently send a new message whenever
	// the service's serving status changes.
	//
	// If the requested service is unknown when the call is received, the
	// server will send a message setting the serving status to
	// SERVICE_UNKNOWN but will *not* terminate the call.  If at some
	// future point, the serving status of the service becomes known, the
	// server will send a new message with the service's serving status.
	//
	// If the call terminates with status UNIMPLEMENTED, then clients
	// should assume this method is not supported and should not retry the
	// call.  If the call terminates with any other status (including OK),
	// clients should retry the call with appropriate exponential backoff.
	Watch(*HealthCheckRequest, Health_WatchServer) error
}

我们将这两个接口进行简单的实现

type Service struct {}

func (h  Service) Check(context.Context, *grpc_health_v1.HealthCheckRequest) (*grpc_health_v1.HealthCheckResponse, error) {
	return &grpc_health_v1.HealthCheckResponse{Status: grpc_health_v1.HealthCheckResponse_SERVING} , nil
}

func (h Service) Watch(*grpc_health_v1.HealthCheckRequest, grpc_health_v1.Health_WatchServer) error{
	return nil
}

我们在进行服务注册和健康检查时的配置

func (c ConsulRegister) Register() {
	config := &api.AgentServiceRegistration{
		Address: "127.0.0.1",
		Port: 8085,
		Name: "healthname",
		ID: "healthid",
		Check: &api.AgentServiceCheck{
			GRPC: "127.0.0.1:8085/Health",
			Interval: "5s",
			Timeout: "5s",
		},
	}
	c.Client.Register(config)
}

这样,进行服务注册之后,就会进行健康检查。


版权声明:本文为Xiang_lhh原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。