6.使用Go向Consul注冊的基本方法


編寫注冊函數

package utils

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

func RegService() {
    config := consulapi.DefaultConfig()
    config.Address = "192.168.3.14:8500"
    reg := consulapi.AgentServiceRegistration{}
    reg.Name = "userservice" //注冊service的名字
    reg.Address = "192.168.3.14" //注冊service的ip
    reg.Port = 8080//注冊service的端口
    reg.Tags = []string{"primary"}

    check := consulapi.AgentServiceCheck{} //創建consul的檢查器
    check.Interval="5s" //設置consul心跳檢查時間間隔
    check.HTTP = "http://192.168.3.14:8080/health" //設置檢查使用的url

    reg.Check = &check

    client, err := consulapi.NewClient(config) //創建客戶端
    if err != nil {
        log.Fatal(err)
    }
    err = client.Agent().ServiceRegister(&reg)
    if err != nil {
        log.Fatal(err)
    }
}

調用注冊函數

package main

import (
    httptransport "github.com/go-kit/kit/transport/http"
    mymux "github.com/gorilla/mux"
    "gomicro/Services"
    "gomicro/utils"
    "net/http"
)

func main() {
    user := Services.UserService{}
    endp := Services.GenUserEnPoint(user)

    serverHandler := httptransport.NewServer(endp, Services.DecodeUserRequest, Services.EncodeUserResponse) //使用go kit創建server傳入我們之前定義的兩個解析函數

    r := mymux.NewRouter()
    //r.Handle(`/user/{uid:\d+}`, serverHandler) //這種寫法支持多種請求方式
    r.Methods("GET", "DELETE").Path(`/user/{uid:\d+}`).Handler(serverHandler) //這種寫法僅支持Get,限定只能Get請求
    r.Methods("GET").Path("/health").HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
        writer.Header().Set("Content-type", "application/json")
        writer.Write([]byte(`{"status":"ok"}`))
    })
    utils.RegService() //調用注冊服務程序
    http.ListenAndServe(":8080", r)

}





免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM