介绍
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
", 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
", r.Node.Key, r.Node.Value)
}
}
}
func Close() {
if nil != client {
client.Close()
}
log.Println("Stop")
}