Home / PostsPost
golang consul 注册服务
嘟噜聪2022/03/25 17:45:00 [Golang] [kplcloud] [go-kit] [consul] [注册中心] [服务发现] 1194人已阅
简介 介绍一个 go-kit 注册到consul的简单案例,废话不多说,直接上源码。![](http://source.qiniu.cnd.nsini.com/images/2022/03/fd/9
介绍一个 go-kit 注册到consul的简单案例,废话不多说,直接上源码。
记住,进程不要用 kill -9
杀掉,请用kill
, 因为 kill -9
是无视进程的后续处理,会直接回收资源。
import (
consulsd "github.com/go-kit/kit/sd/consul"
consulapi "github.com/hashicorp/consul/api"
)
var (
appName = "user.center"
httpAddr = ":8080"
Version = "v0.0.1"
client consulsd.Client
registrar *consulsd.Registrar
)
func registerConsul() {
port, _ := strconv.Atoi(strings.TrimLeft(httpAddr, ":"))
var tags = []string{appName, Version}
registration := new(consulapi.AgentServiceRegistration)
registration.ID = uuid.New().String()
registration.Name = appName
registration.Port = port
registration.Tags = tags
registration.Address = getLocalAddr()
registration.Check = &consulapi.AgentServiceCheck{
Timeout: "5s",
Interval: "5s",
DeregisterCriticalServiceAfter: "30s", // 故障检查失败30s后 consul自动将注册服务删除
HTTP: fmt.Sprintf("http://%s:%d/health", registration.Address, registration.Port),
}
registrar = consulsd.NewRegistrar(client, registration, logger)
registrar.Register()
}
// 获取本机地址
func getLocalAddr() string {
addrs, err := net.InterfaceAddrs()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
for _, address := range addrs {
// 检查ip地址判断是否回环地址
if ipNet, ok := address.(*net.IPNet); ok && !ipNet.IP.IsLoopback() {
if ipNet.IP.To4() != nil {
return ipNet.IP.String()
}
}
}
return ""
}
// 注销服务
func serviceDeregister() {
if client == nil {
return
}
registrar.Deregister()
}
尾巴
不用多说了,懂的都懂。
很赞哦! (3)