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的方式,用起来体验会更好一点。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值