consul使用

安装consul

  下载地址 https://releases.hashicorp.com/consul/,将下载的consul.exe 文件目录添加到系统环境中,然后执行   consul agent -dev  启动,默认监听8500端口,可以访问 http://127.0.0.1:8500/ 进行查看

在golang项目中安装consul

go get github.com/hashicorp/consul

代码:

server.go 注册服务

package main

import (
	"fmt"
	consulapi "github.com/hashicorp/consul/api"
)

func main() {

	consulConfig := consulapi.DefaultConfig()

	fmt.Println(consulConfig)

	consulClient, err := consulapi.NewClient(consulConfig)
	if err != nil {
		fmt.Println(err)
	}

	registerService := consulapi.AgentServiceRegistration{
		ID:      "1",
		Tags:    []string{"grpctest"},
		Port:    8082,
		Name:    "grpc api",
		Address: "127.0.0.1",
		Check: &consulapi.AgentServiceCheck{
			CheckID:  "grpc api",
			Interval: "5s",
			Timeout:  "5s",
			TCP:      "127.0.0.1:8082",
		},
	}

	err = consulClient.Agent().ServiceRegister(&registerService)
	fmt.Println(err)

}

client.go 发现可用服务

package main

import (
	"fmt"
	consulapi "github.com/hashicorp/consul/api"
)

func main() {

	consulConf := consulapi.DefaultConfig()
	consulClient, err := consulapi.NewClient(consulConf)
	if err != nil {
		fmt.Println(err)
	}

	serviceEntry, _, _ := consulClient.Health().Service("grpc api", "grpctest", false, &consulapi.QueryOptions{})

	fmt.Println(serviceEntry[0].Service.Address)
	fmt.Println(serviceEntry[0].Service.Port)
}

 删除服务 destroy.go

package main

import (
	"fmt"
	consulapi "github.com/hashicorp/consul/api"
)

func main() {
	consulConf := consulapi.DefaultConfig()
	cli, err := consulapi.NewClient(consulConf)
	if err != nil {
		fmt.Println(err)
	}

	err = cli.Agent().ServiceDeregister("1")
	fmt.Println(err)
}

  

 

 

 

 

  

posted @ 2021-05-04 13:22  GPHPER  阅读(199)  评论(0编辑  收藏  举报
TOP