在微服务架构里面,每个小服务都是由很多节点组成,节点的添加删除故障希望能对下游透明,因此有必要引入一种服务的自动注册和发现机制,而 consul 提供了完整的解决方案,并且内置了对 GRPC 以及 HTTP 服务的支持

总体架构

  1. 服务调用: client 直连 server 调用服务
  2. 服务注册: 服务端将服务的信息注册到 consul 里
  3. 服务发现: 客户端从 consul 里发现服务信息,主要是服务的地址
  4. 健康检查: consul 检查服务器的健康状态

服务注册

服务端将服务信息注册到 consul 里,这个注册可以在服务启动可以提供服务的时候完成

完整代码参考: https://github.com/hatlonely/hellogolang/blob/master/sample/addservice/internal/grpcsr/consul_register.go

服务发现

客户端从 consul 里发现服务信息,主要是服务的地址

完整代码参考: https://github.com/hatlonely/hellogolang/blob/master/sample/addservice/internal/grpclb/consul_resolver.go

健康检查

consul 检查服务器的健康状态,consul 用 google.golang.org/grpc/health/grpc_health_v1.HealthServer 接口,实现了对 grpc健康检查的支持,所以我们只需要实现先这个接口,consul 就能利用这个接口作健康检查了

完整代码参考: https://github.com/hatlonely/hellogolang/blob/master/sample/addservice/cmd/server/main.go

参考链接

完整工程代码: https://github.com/hatlonely/hellogolang/tree/master/sample/addservice
consul 健康检查 api: https://www.consul.io/api/agent/check.html
consul 服务注册 api: https://www.consul.io/api/agent/service.html
grpc 健康检查: https://github.com/grpc/grpc/blob/master/doc/health-checking.md

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。