Go 使用 clientv3 连接 etcd


etcd3 和 etcd2 的 api 不太一样。
etcd3 移除了目录概念,只有单纯的 kv。
api 也只有 rpc 模式,http 需要 proxy。

package etcd

import (
    "context"
    "log"
    "time"

    "../conf"

    "go.etcd.io/etcd/clientv3"
)

var (
    endpoints   = make([]string, 1)
    dialTimeout = 3 * time.Second
    username    string
    password    string
)

// Init is init etcd
func Init() {
    endpoints = append(endpoints, conf.RunTimeInfo.EtcdHost)
    username = conf.RunTimeInfo.EtcdUser
    password = conf.RunTimeInfo.EtcdPasswd
}

// connetEtcd is connect etcd
func connetEtcd() *clientv3.Client {
    cli, cliErr := clientv3.New(clientv3.Config{
        Endpoints:   endpoints,
        DialTimeout: dialTimeout,
        Username:    username,
        Password:    password,
    })
    if cliErr != nil {
        log.Println(cliErr)
    }
    return cli
}

// KeepAlive is make etcd keepalive with ttl
func KeepAlive(keyID clientv3.LeaseID) {
    cli := connetEtcd()
    if cli != nil {
        ka, kaErr := cli.KeepAliveOnce(context.TODO(), keyID)
        if kaErr != nil {
            log.Println(kaErr)
        }
        log.Println("ttl:", ka)
        cli.Close()
    }
}

// GetKV is get kv from etcd
func GetKV(dir string) []string {
    cli := connetEtcd()
    var kvList = make([]string, 0)
    if cli != nil {
        resp, respErr := cli.Get(context.TODO(), dir, clientv3.WithPrefix())
        if respErr != nil {
            log.Println(respErr)
        }
        for _, ev := range resp.Kvs {
            kvTemp := string(ev.Key) + ":" + string(ev.Value)
            kvList = append(kvList, kvTemp)
        }
        cli.Close()
    }
    return kvList
}

// PutKV is set kv to etcd
func PutKV(writePath string, writeValue string) {
    cli := connetEtcd()
    if cli != nil {
        resp, respErr := cli.Put(context.TODO(), writePath, writeValue)
        if respErr != nil {
            log.Println(respErr)
        }
        if resp != nil {
            log.Println(resp.Header)
            cli.Close()
        }
    }
}

// PutKVTTL is set kv to etcd with ttl
func PutKVTTL(registKey, registValue string) {
    cli := connetEtcd()
    if cli != nil {
        resp, respErr := cli.Grant(context.TODO(), 10)
        if respErr != nil {
            log.Println(respErr)
        }
        conf.ServID = resp.ID
        putResp, putErr := cli.Put(context.TODO(), registKey, registValue, clientv3.WithLease(resp.ID))
        if putErr != nil {
            log.Println(putErr)
        }
        log.Println(putResp.Header)
        cli.Close()
    }
}

// DelKV is del kv to etcd
func DelKV(writePath string) {
    cli := connetEtcd()
    if cli != nil {
        resp, respErr := cli.Delete(context.TODO(), writePath)
        if respErr != nil {
            log.Println(respErr)
        }
        log.Println(resp.Header)
        cli.Close()
    }
}
分享:

评论