From e386683768c4953ae0968117026e98af9fba6d51 Mon Sep 17 00:00:00 2001 From: "suguo.yao" Date: Fri, 17 Sep 2021 16:36:23 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0RegisterAPI?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- consul/consul.go | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/consul/consul.go b/consul/consul.go index d11a32f..8d2d1f6 100644 --- a/consul/consul.go +++ b/consul/consul.go @@ -50,6 +50,40 @@ func New() (*consulapi.Client, error) { return client, nil } +//RegisterAPI 注册api服务到consul +func RegisterAPI(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.HTTP = fmt.Sprintf("http://%s:%d/health/check", 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 +} + //Register 注册服务到consul func Register(name string, addr string, port int, tags ...string) error { client, err := New()