7.Go退出向Consuk反注册服务,优雅关闭服务

注册和反注册代码

package utils

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

var ConsulClient *consulapi.Client

func init() {
    config := consulapi.DefaultConfig()
    config.Address = "192.168.3.14:8500"
    client, err := consulapi.NewClient(config) //创建客户端
    if err != nil {
        log.Fatal(err)
    }
    ConsulClient = client
}

func RegService() {
    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

    err := ConsulClient.Agent().ServiceRegister(®)
    if err != nil {
        log.Fatal(err)
    }

}

func UnRegService() {
    ConsulClient.Agent().ServiceDeregister("userservice")
}

service退出时优雅反注册service

package main

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

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)

    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"}`))
    })//这种写法仅支持Get限定只能Get,DELETE请求
    errChan := make(chan error)
    go func() {
        utils.RegService() //调用注册服务程序
        err := http.ListenAndServe(":8080", r)
        if err != nil {
            log.Println(err)
            errChan <- err
        }
    }()
    go func() {
        sigChan := make(chan os.Signal)
        signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
        errChan <- fmt.Errorf("%s", <-sigChan)
    }()
    getErr := <-errChan //只要报错 或者service关闭阻塞在这里的会进行下去
    utils.UnRegService()
    log.Println(getErr)
}


来自为知笔记(Wiz)


你可能感兴趣的:(7.Go退出向Consuk反注册服务,优雅关闭服务)