Fetch the repository succeeded.
package consul
import (
"fmt"
"io/ioutil"
"gitee.com/natas-public/utils/net"
"gitee.com/natas-public/utils/str"
consulApi "github.com/hashicorp/consul/api"
yaml "gopkg.in/yaml.v2"
)
type Config struct {
Consul struct {
Server string `yaml:"server"`
Port string `yaml:"port"`
ID string `yaml:"id"`
Name string `yaml:"name"`
Tags []string `yaml:"tags,flow"`
Timeout int `yaml:"timeout"`
Interval int `yaml:"interval"`
Dcsafter int `yaml:"dcsafter"`
Client struct {
IP string `yaml:"ip"`
Port int `yaml:"port"`
Health string `yaml:"health"`
} `yaml:"client"`
} `yaml:"consul"`
}
var (
client *consulApi.Client
)
func Register() error {
var (
err error
ymlConf []byte
)
if ymlConf, err = ioutil.ReadFile("./conf/consul.yml"); nil != err {
return err
}
config := new(Config)
config.Consul.ID = str.GetRandomString(8)
config.Consul.Name = str.GetRandomString(16)
config.Consul.Client.IP = net.GetLocalIP()
config.Consul.Timeout = 5
config.Consul.Interval = 5
config.Consul.Dcsafter = 30
if err = yaml.Unmarshal(ymlConf, config); nil != err {
return err
}
consulConfig := consulApi.DefaultConfig()
consulConfig.Address = fmt.Sprintf("%s:%s", config.Consul.Server, config.Consul.Port)
if client, err = consulApi.NewClient(consulConfig); nil != err {
return err
}
// 创建注册到consul的服务到
registration := new(consulApi.AgentServiceRegistration)
registration.ID = config.Consul.ID
registration.Name = config.Consul.Name
registration.Port = config.Consul.Client.Port
registration.Tags = config.Consul.Tags
registration.Address = config.Consul.Client.IP
// 增加consul健康检查回调函数
check := new(consulApi.AgentServiceCheck)
check.HTTP = fmt.Sprintf("http://%s:%d%s", registration.Address, registration.Port, config.Consul.Client.Health)
check.Timeout = fmt.Sprintf("%ds", config.Consul.Timeout)
check.Interval = fmt.Sprintf("%ds", config.Consul.Interval)
check.DeregisterCriticalServiceAfter = fmt.Sprintf("%ds", config.Consul.Dcsafter) // 故障检查失败30s后 consul自动将注册服务删除
registration.Check = check
// 注册服务到consul
if err = client.Agent().ServiceRegister(registration); nil != err {
return err
}
return nil
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。