Consul 安装和UI

Consul 安装和UI,第1张

CentOS/RHEL

Downloads | Consul by HashiCorp

sudo yum install -y yum-utils
sudo yum-config-manager --add-repo https://rpm.releases.hashicorp.com/RHEL/hashicorp.repo
sudo yum -y install consul

访问ui

consul agent -dev -client 0.0.0.0 -ui

Linux,一定要关闭防火墙,Windows一定要开端口

http://192.168.10.50:8500/ui/dc1/services

demo地址

golang 使用 consul 做服务发现 - 追逐~~~ - 博客园

服务器代码

package main


import (
   "fmt"
   "log"
   "net"
   "net/http"
   _ "net/http/pprof"


   consulapi "github.com/hashicorp/consul/api"
)


var count int64


// consul 服务端会自己发送请求,来进行健康检查
func consulCheck(w http.ResponseWriter, r *http.Request) {


   s := "consulCheck" + fmt.Sprint(count) + "remote:" + r.RemoteAddr + " " + r.URL.String()
   fmt.Println(s)
   fmt.Fprintln(w, s)
   count++
}


func registerServer() {


   config := consulapi.DefaultConfig()
   config.Address = "192.168.10.50:8500"
   client, err := consulapi.NewClient(config)
   if err != nil {
      log.Fatal("consul client error : ", err)
   }


   registration := new(consulapi.AgentServiceRegistration)
   registration.ID = "serverNode_1"      // 服务节点的名称
   registration.Name = "serverNode"      // 服务名称
   registration.Port = 9527              // 服务端口
   registration.Tags = []string{"v1000"} // tag,可以为空
   registration.Address = localIP()      // 服务 IP


   checkPort := 9130 //linux可以访问的端口
   registration.Check = &consulapi.AgentServiceCheck{ // 健康检查
      HTTP:                           fmt.Sprintf("http://%s:%d%s", registration.Address, checkPort, "/check"),
      Timeout:                        "3s",
      Interval:                       "5s",  // 健康检查间隔
      DeregisterCriticalServiceAfter: "30s", //check失败后30秒删除本服务,注销时间,相当于过期时间
      // GRPC:     fmt.Sprintf("%v:%v/%v", IP, r.Port, r.Service),// grpc 支持,执行健康检查的地址,service 会传到 Health.Check 函数中
   }


   err = client.Agent().ServiceRegister(registration)
   if err != nil {
      log.Fatal("register server error : ", err)
   }


   http.HandleFunc("/check", consulCheck)
   http.ListenAndServe(fmt.Sprintf(":%d", checkPort), nil)


}


func localIP() string {
   addrs, err := net.InterfaceAddrs()
   if err != nil {
      return ""
   }
   for _, address := range addrs {
      if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
         if ipnet.IP.To4() != nil {
            return ipnet.IP.String()
         }
      }
   }
   return ""
}


func main() {
   registerServer()
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/995845.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存