在微服務架構裏面,每一個小服務都是由不少節點組成,節點的添加刪除故障但願能對下游透明,所以有必要引入一種服務的自動註冊和發現機制,而 consul 提供了完整的解決方案,而且內置了對 GRPC 以及 HTTP 服務的支持html
服務端將服務信息註冊到 consul 裏,這個註冊能夠在服務啓動能夠提供服務的時候完成git
完整代碼參考: https://github.com/hatlonely/...github
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 裏發現服務信息,主要是服務的地址golang
完整代碼參考: https://github.com/hatlonely/...api
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/...架構
// 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{})
轉載請註明出處
本文連接: http://www.hatlonely.com/2018...