zoukankan      html  css  js  c++  java
  • consul golang

    服务注册:

    package main
    
    import (
    	"log"
    	"github.com/gin-gonic/gin"
    	consulapi "github.com/hashicorp/consul/api"
    	"fmt"
    	"net/http"
    )
    
    
    func main() {
    
    	// 服务注册
    	registerServer()
    
    	r := gin.Default()
    	r.GET("/ping", heathCheck)
    	r.Run()
    }
    
    // consul 服务注册
    func registerServer()  {
    
    	// 创建consul客户端
    	config := consulapi.DefaultConfig()
    	config.Address = "172.16.30.129:8500"
    	client, err := consulapi.NewClient(config)
    	if err != nil {
    		log.Fatal("consul client error : ", err)
    	}
    
    	registration := new(consulapi.AgentServiceRegistration)
    	registration.ID = "c1"      // 服务节点的名称
    	registration.Name = "wsp"      // 服务名称
    	registration.Port = 8080              // 服务端口
    	registration.Tags = []string{"wsp"} // tag,可以为空
    	registration.Address = "192.168.43.253"      // 服务 IP
    
    	// 健康检查 支持http及grpc 回调接口
    	checkPort := 8080
    	registration.Check = &consulapi.AgentServiceCheck{ // 健康检查
    		HTTP:                           fmt.Sprintf("http://%s:%d%s", registration.Address, checkPort, "/ping"),
    		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)
    	}
    }
    
    // consul 健康检测
    func heathCheck(c *gin.Context)  {
    	c.JSON(http.StatusOK, "ok")
    }
    

      服务发现:

    package main
    
    import (
    	"log"
    	consulapi "github.com/hashicorp/consul/api"
    	"fmt"
    )
    
    
    func main() {
    
    	// 服务发现
    	discoverServer()
    }
    
    // consul 服务注册
    func discoverServer()  {
    
    	// 创建consul客户端
    	config := consulapi.DefaultConfig()
    	config.Address = "172.16.30.129:8500"
    	client, err := consulapi.NewClient(config)
    	if err != nil {
    		log.Fatal("consul client error : ", err)
    	}
    
    	// 服务发现
    	services, _, err := client.Health().Service("wsp", "wsp", true, &consulapi.QueryOptions{})
    	if err != nil {
    		log.Println("error retrieving instances from Consul: %v", err)
    	}
    	// service 遍历
    	for _, service := range services {
    		fmt.Println("service.Service.Address:", service.Service.Address, "service.Service.Port:", service.Service.Port)
    	}
    }
    

      kv存储:

    package main
    
    import (
    	"log"
    	consulapi "github.com/hashicorp/consul/api"
    	"fmt"
    	"code.admaster.co/social/tuice-wechat/data"
    )
    
    
    func main() {
    
    	// 创建consul客户端
    	config := consulapi.DefaultConfig()
    	config.Address = "172.16.30.129:8500"
    	client, err := consulapi.NewClient(config)
    	if err != nil {
    		log.Fatal("consul client error : ", err)
    	}
    	//kv := &consulapi.KVPair{Key:"wsp", Value:[]byte(`{"level":"info"}`)}
    	//client.KV().Put(kv, nil)
    	data, _ , _ := client.KV().Get("wsp", nil)
    	fmt.Println(string(data.Value))
    
    }
    

      watch机制:

    package main
    
    import (
    	"log"
    	"github.com/gin-gonic/gin"
    	consulapi "github.com/hashicorp/consul/api"
    	"fmt"
    	"net/http"
    )
    
    
    func main() {
    
    	r := gin.Default()
    	r.GET("/watch", heathCheck2)
    	r.Run(":8081")
    }
    
    // consul 健康检测
    func heathCheck2(c *gin.Context)  {
    	config := consulapi.DefaultConfig()
    	config.Address = "172.16.30.129:8500"
    	client, err := consulapi.NewClient(config)
    	if err != nil {
    		log.Fatal("consul client error : ", err)
    	}
    	data, _ , _ := client.KV().Get("wsp", nil)
    	fmt.Println(string(data.Value))
    	c.JSON(http.StatusOK, "ok")
    }
    

      配置文件:

    {
      "watches": [
        {
          "type": "key",
          "key": "wsp",
          "handler_type": "http",
          "http_handler_config": {
             "path":"http://192.168.43.253:8081/watch",
             "method": "GET",
             "timeout": "10s",
             "tls_skip_verify": false
          }
        }
      ]
    }
    

      

  • 相关阅读:
    PTA乙级 (*1034 有理数四则运算 (20分)(string.append()))
    Nginx反向代理部署Node.js应用配置方法
    js处理字符串的用法小结
    从零开始基于webpack搭建react全家桶
    Linux常用指令
    matplotlib作图时中文字体乱码解决办法
    大话数据结构 串
    大话数据结构 队列
    大话数据结构 栈
    大话数据结构 线性表
  • 原文地址:https://www.cnblogs.com/hcy-fly/p/12006745.html
Copyright © 2011-2022 走看看