在微服務架構里面,每個小服務都是由很多節點組成,節點的添加刪除故障希望能對下游透明,因此有必要引入一種服務的自動注冊和發現機制,而 consul 提供了完整的解決方案,并且內置了對 GRPC 以及 HTTP 服務的支持
總體架構

- 服務調用: client 直連 server 調用服務
- 服務注冊: 服務端將服務的信息注冊到 consul 里
- 服務發現: 客戶端從 consul 里發現服務信息,主要是服務的地址
- 健康檢查: consul 檢查服務器的健康狀態
服務注冊
服務端將服務信息注冊到 consul 里,這個注冊可以在服務啟動可以提供服務的時候完成
完整代碼參考: https://github.com/hatlonely/hellogolang/blob/master/sample/addservice/internal/grpcsr/consul_register.go
config := api.DefaultConfig()
config.Address = r.Address
client, err := api.NewClient(config)
if err != nil {
panic(err)
}
agent := client.Agent()
IP := localIP()
reg := api.AgentServiceRegistration{
ID: fmt.Sprintf("%v-%v-%v", r.Service, IP, r.Port), // 服務節點的名稱
Name: fmt.Sprintf("grpc.health.v1.%v", r.Service), // 服務名稱
Tags: r.Tag, // tag,可以為空
Port: r.Port, // 服務端口
Address: IP, // 服務 IP
Check: api.AgentServiceCheck{ // 健康檢查
Interval: r.Interval.String(), // 健康檢查間隔
// grpc 支持,執行健康檢查的地址,service 會傳到 Health.Check 函數中
GRPC: fmt.Sprintf("%v:%v/%v", IP, r.Port, r.Service),
DeregisterCriticalServiceAfter: r.DeregisterCriticalServiceAfter.String(), // 注銷時間,相當于過期時間
},
}
if err := agent.ServiceRegister(reg); err != nil {
panic(err)
}
服務發現
客戶端從 consul 里發現服務信息,主要是服務的地址
完整代碼參考: https://github.com/hatlonely/hellogolang/blob/master/sample/addservice/internal/grpclb/consul_resolver.go
services, metainfo, err := w.client.Health().Service(w.service, "", true, api.QueryOptions{
WaitIndex: w.lastIndex, // 同步點,這個調用將一直阻塞,直到有新的更新
})
if err != nil {
logrus.Warn("error retrieving instances from Consul: %v", err)
}
w.lastIndex = metainfo.LastIndex
addrs := map[string]struct{}{}
for _, service := range services {
addrs[net.JoinHostPort(service.Service.Address, strconv.Itoa(service.Service.Port))] = struct{}{}
}
健康檢查
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
// HealthImpl 健康檢查實現
type HealthImpl struct{}
// Check 實現健康檢查接口,這里直接返回健康狀態,這里也可以有更復雜的健康檢查策略,比如根據服務器負載來返回
func (h *HealthImpl) Check(ctx context.Context, req *grpc_health_v1.HealthCheckRequest) (*grpc_health_v1.HealthCheckResponse, error) {
return grpc_health_v1.HealthCheckResponse{
Status: grpc_health_v1.HealthCheckResponse_SERVING,
}, nil
}
grpc_health_v1.RegisterHealthServer(server, HealthImpl{})
參考鏈接
完整工程代碼: 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
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
您可能感興趣的文章:- Golang實現的聊天程序服務端和客戶端代碼分享
- golang實現簡單的udp協議服務端與客戶端示例
- 詳解如何熱重啟golang服務器
- golang搭建靜態web服務器的實現方法
- golang websocket 服務端的實現
- 詳解prometheus監控golang服務實踐記錄