Golang consul 服务注册与发现
Posted Time-Traveler
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Golang consul 服务注册与发现相关的知识,希望对你有一定的参考价值。
下载运行consul:
consul下载地址: https://www.consul.io/downloads 命令行运行:consul.exe agent -dev
运行之后在127.0.0.1:8500这个地址上有个ui界面,可供查看:
服务注册:
package main
import (
"fmt"
"github.com/go-basic/uuid"
consulapi "github.com/hashicorp/consul/api"
"net/http"
)
const (
consulAddress = "127.0.0.1:8500"
localIp = "127.0.0.1"
localPort = 8090
servicePort = 9000
)
func consulRegister() {
// 创建连接consul服务配置
config := consulapi.DefaultConfig()
config.Address = consulAddress
client, err := consulapi.NewClient(config)
if err != nil {
fmt.Println("consul client error : ", err)
}
// 创建注册到consul的服务到
registration := new(consulapi.AgentServiceRegistration)
registration.ID = uuid.New()
registration.Name = "service"
registration.Port = servicePort
registration.Tags = []string{"testService"}
registration.Address = localIp
// 增加consul健康检查回调函数
check := new(consulapi.AgentServiceCheck)
check.HTTP = fmt.Sprintf("http://%s:%d", registration.Address, localPort)
check.Timeout = "5s"
check.Interval = "5s"
check.DeregisterCriticalServiceAfter = "30s" // 故障检查失败30s后 consul自动将注册服务删除
registration.Check = check
// 注册服务到consul
err = client.Agent().ServiceRegister(registration)
}
func Handler(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("health check api"))
}
func main() {
consulRegister()
http.HandleFunc("/", Handler)
err := http.ListenAndServe(fmt.Sprintf("0.0.0.0:%d", localPort), nil)
if err != nil {
fmt.Println("error: ", err.Error())
}
}
go-micro中提供了另一种方式注册,大家可以去看看。
服务发现:
package main
import (
"fmt"
"github.com/micro/go-micro/v2/client/selector"
"github.com/micro/go-micro/v2/registry"
"github.com/micro/go-plugins/registry/consul/v2"
)
var reg registry.Registry
func init() {
reg = consul.NewRegistry(registry.Addrs("127.0.0.1:8500"))
}
func GetServiceAddress(name string) (address string) {
list,_ := reg.GetService(name)
var services []*registry.Service
for _,value := range list{
services = append(services, value)
}
next := selector.RoundRobin(services)
if node, err := next(); err == nil {
address = node.Address
}
return
}
func main() {
address := GetServiceAddress("service")
fmt.Printf("address is: %s\\n", address)
}
服务发现V2:
package main
import (
"fmt"
consulapi "github.com/hashicorp/consul/api"
)
const (
consulAgentAddress = "127.0.0.1:8500"
)
// 从consul中发现服务
func FindService() {
// 创建连接consul服务配置
config := consulapi.DefaultConfig()
config.Address = consulAgentAddress
client, err := consulapi.NewClient(config)
if err != nil {
fmt.Println("consul client error : ", err)
return
}
// 获取指定service
services, _ := client.Agent().Services()
for _, service := range services {
fmt.Printf("service address is:%s:%d service name is:%s\\n", service.Address, service.Port, service.Service)
}
//service, _, err := client.Agent().Service("serviceId", nil)
//if err != nil{
// fmt.Println("consul get service error : ", err)
// return
//}
//fmt.Printf("address is:%s:%d\\n", service.Address, service.Port)
//只获取健康的service
serviceHealthy, _, err := client.Health().Service("service", "", true, nil)
if err != nil {
fmt.Println("consul get health service error : ", err)
return
}
fmt.Println("serviceHealthy is:", serviceHealthy[0].Node.Address)
}
func main() {
FindService()
}
前面那个版本实现了RoundRobin的方式,用起来体验会更好一点。
以上是关于Golang consul 服务注册与发现的主要内容,如果未能解决你的问题,请参考以下文章
Golang 语言微服务的服务发现组件 Consul 的系统架构介绍