增加RegisterAPI

This commit is contained in:
suguo.yao 2021-09-17 16:36:23 +08:00
parent 44b1fba8c8
commit e386683768
1 changed files with 34 additions and 0 deletions

View File

@ -50,6 +50,40 @@ func New() (*consulapi.Client, error) {
return client, nil 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 //Register 注册服务到consul
func Register(name string, addr string, port int, tags ...string) error { func Register(name string, addr string, port int, tags ...string) error {
client, err := New() client, err := New()