etcd介绍与使用
@H_403_26@概念:高可用的分布式key-value存储,可以用于配置共享和服务发现。类似项目:zookeeper和consul
开发语言:Go
接口:提供restful的http接口,使用简单
实现算法:基于raft算法的强一致性、高可用的服务存储目录 @H_403_26@etcd搭建
a. 下载etcd release版本:@L_404_4@
b. ./bin/etcd即可以启动etcd
c. 使用etcdctl工具更改配置
etcd测试链接
package main
import (
"fmt"
"github.com/coreos/etcd/clientv3"
"time"
)
func main() {
/*
DialTimeout time.Duration `json:"dial-timeout"`
Endpoints []string `json:"endpoints"`
*/
cli,err := clientv3.New(clientv3.Config{
Endpoints: []string{"localhost:2379","localhost:22379","localhost:32379"},DialTimeout: 5 * time.Second,})
if err != nil {
fmt.Println("connect Failed,err:",err)
return
}
fmt.Println("connect succ")
defer cli.Close()
}
@H_403_26@输出如下:
PS E:\golang\go_pro\src\safly> go run main.go
connect succ
PS E:\golang\go_pro\src\safly>
etcd存取值
package main
import (
"context"
"fmt"
"github.com/coreos/etcd/clientv3"
"time"
)
func main() {
cli,err := clientv3.New(clientv3.Config{
Endpoints: []string{"localhost:2379",DialTimeout: 5 * time.Second,})
if err != nil {
fmt.Println("connect Failed,err)
return
}
fmt.Println("connect succ")
defer cli.Close()
//设置1秒超时,访问etcd有超时控制
ctx,cancel := context.WithTimeout(context.Background(),time.Second)
//操作etcd
_,err = cli.Put(ctx,"/logagent/conf/","sample_value")
//操作完毕,取消etcd
cancel()
if err != nil {
fmt.Println("put Failed,err)
return
}
//取值,设置超时为1秒
ctx,cancel = context.WithTimeout(context.Background(),time.Second)
resp,err := cli.Get(ctx,"/logagent/conf/")
cancel()
if err != nil {
fmt.Println("get Failed,err)
return
}
for _,ev := range resp.Kvs {
fmt.Printf("%s : %s\n",ev.Key,ev.Value)
}
}
@H_403_26@输出如下:
PS E:\golang\go_pro\src\safly> go run example.go
connect succ
/logagent/conf/ : sample_value
etcd检测Watch
package main
import (
"context"
"fmt"
"time"
"github.com/coreos/etcd/clientv3"
)
func main() {
cli,err)
return
}
fmt.Println("connect succ")
defer cli.Close()
cli.Put(context.Background(),"8888888")
for {
rch := cli.Watch(context.Background(),"/logagent/conf/")
for wresp := range rch {
for _,ev := range wresp.Events {
fmt.Printf("%s %q : %q\n",ev.Type,ev.Kv.Key,ev.Kv.Value)
}
}
}
}