1 Star 0 Fork 0

natas-public/beego-utils

Create your Gitee Account
Explore and code with more than 13.5 million developers,Free private repositories !:)
Sign up
文件
Clone or Download
consul.go 2.51 KB
Copy Edit Raw Blame History
徐文越 authored 2022-10-13 10:18 +08:00 . v0.1.1 增加consul微服务组件
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
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/natas-public/beego-utils.git
git@gitee.com:natas-public/beego-utils.git
natas-public
beego-utils
beego-utils
v0.1.1

Search