golang 中 etcd 基本用法

介绍

ETCD : 高可用的分布式key-value存储,可以用于配置共享和服务发现。
类似项目:zookeeper和consul

import (
	"github.com/coreos/go-etcd/etcd"
	"log"
)

var (
	client *etcd.Client
	machines = []string{"http://127.0.0.1:2379"}
)

// 在初始化方法中创建 etcd 客户端
func init()  {
	client = etcd.NewClient(machines)
	log.Print("etcd client create success")
}

// 设置key值
func SetKey(key,value string,ttl uint64) {
	if nil == client {
		log.Fatal("etcd client is nil")
		return
	}
	if _, err := client.Set(key, value, ttl); err != nil {
		log.Fatal(err)
	}
}

// 获取key值
func GetKey(key string)  {
	if nil == client {
		log.Fatal("etcd client is nil")
		return
	}
	resp, err := client.Get(key, false, false)
	if err != nil {
		log.Fatal(err)
	}
	log.Printf("Current creds: %s: %s\n", resp.Node.Key, resp.Node.Value)
}

// 监听key值的滨化
func WatchKey(key string)  {
	if nil == client {
		log.Fatal("etcd client is nil")
		return
	}
	receiver := make(chan *etcd.Response)
	stopChan := make(chan bool)
	go client.Watch(key,0,false,receiver,stopChan)
	for  {
		select {
		case r := <-receiver:
			if r.Node.Value == "stop"{
				stopChan<- true
				log.Println("get stop")
				return
			}
			log.Printf("Got updated creds: %s: %s\n", r.Node.Key, r.Node.Value)

		}
	}
}

func Close()  {
	if nil != client {
		client.Close()
	}
	log.Println("Stop")
}
posted @ 2018-09-10 18:09  熊二  阅读(2916)  评论(0编辑  收藏  举报