From 6903a40cc2e51819ca556531d13db21b0a6ce119 Mon Sep 17 00:00:00 2001 From: "suguo.yao" Date: Fri, 8 Oct 2021 15:05:46 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8Dregister=E8=AF=AF=E5=88=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- consul/consul.go | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/consul/consul.go b/consul/consul.go index 615d37e..c216ebb 100644 --- a/consul/consul.go +++ b/consul/consul.go @@ -50,6 +50,39 @@ func New() (*consulapi.Client, error) { return client, nil } +//Register 注册服务到consul +func Register(name string, addr string, port int, tags ...string) error { + client, err := New() + if err != nil { + return err + } + if client == nil { + return errors.New("consul 实例空") + } + + // 创建注册到consul的服务到 + registration := new(consulapi.AgentServiceRegistration) + registration.ID = fmt.Sprintf("%s-%s:%d", name, addr, port) + registration.Name = name + registration.Port = port + registration.Tags = tags + registration.Address = addr + + // 增加consul健康检查回调函数 + check := new(consulapi.AgentServiceCheck) + check.GRPC = fmt.Sprintf("%s:%d", registration.Address, registration.Port) + check.Timeout = "5s" + check.Interval = "5s" + check.DeregisterCriticalServiceAfter = "30s" // 故障检查失败30s后 consul自动将注册服务删除 + registration.Check = check + + // 注册服务到consul + if err := client.Agent().ServiceRegister(registration); err != nil { + return err + } + return nil +} + //RegisterAPI 注册api服务到consul func RegisterAPI(name string, addr string, port int, tags ...string) error { client, err := New()