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)

}




猜你喜欢

转载自www.cnblogs.com/hualou/p/12080425.html