码迷,mamicode.com
首页 > 其他好文 > 详细

服务关闭时注册和反注册

时间:2019-12-20 09:14:59      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:request   cal   nand   bottom   second   lse   epo   lin   回收   

实现部分

package util

import (
    "context"
    "fmt"
    "go.etcd.io/etcd/clientv3"
    "time"
)

type Service struct {
    client *clientv3.Client
}

func NewService() *Service {
    config := clientv3.Config{
        Endpoints:   []string{"106.12.72.181:23791", "106.12.72.181:23792"},
        DialTimeout: 10 * time.Second,
    }
    client, _ := clientv3.New(config)
    return &Service{client: client}
}
//注册服务
func (this *Service) RegService(id string, name string, address string) error {
    fmt.Println(22)
    kv := clientv3.NewKV(this.client)
    key_prefix := "/services/"
    _, err := kv.Put(context.Background(), key_prefix+id+"/"+name, address)
    fmt.Println(err)
    return err
}

//反注册服务
func (this *Service) UnregService(id string) error {
    kv := clientv3.NewKV(this.client)
    key_prefix := "/services/" + id
    _, err := kv.Delete(context.Background(), key_prefix, clientv3.WithPrefix())
    fmt.Println(err)
    return err
}

执行部分

package main

import (
    "context"
    "fmt"
    "github.com/gorilla/mux"
    "goetcd/util"
    "log"
    "net/http"
    "os"
    "os/signal"
    "strconv"
    "syscall"
)

func main() {
    router := mux.NewRouter()

    router.HandleFunc("/product/{id:\\d+}", func(writer http.ResponseWriter, request *http.Request) {
        vars := mux.Vars(request)
        str := "get product ByID" + vars["id"]
        writer.Write([]byte(str))
    })
    serviceID := "p1"
    serviceName := "productservice"
    serviceAddr := "localhost:"
    servicePort := 8081

    s := util.NewService()
    errChan := make(chan error)
    httpServer := &http.Server{
        Addr:    serviceAddr + strconv.Itoa(servicePort),
        Handler: router, //router实现了ServeHttp方法,所以是Handler接口类型
    }
    go func() {
        err := s.RegService(serviceID, serviceName, serviceAddr+strconv.Itoa(servicePort))
        if err != nil {
            errChan <- err
            return
        }
        err = httpServer.ListenAndServe()
        if err != nil {
            errChan <- err
            return
        }
    }()

    go func() {
        sig := make(chan os.Signal)
        signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
        errChan <- fmt.Errorf("%s", <-sig) //当接收到信号停止
    }()
    getErr := <-errChan
    err := s.UnregService(serviceID) //执行反注册,unset该服务的key
    err = httpServer.Shutdown(context.Background())
    //可以执行一些回收工作,比如关闭数据库
    if err != nil {
        log.Fatal(err)
    }
    log.Fatal(getErr)
}




服务关闭时注册和反注册

标签:request   cal   nand   bottom   second   lse   epo   lin   回收   

原文地址:https://www.cnblogs.com/hualou/p/12071077.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!