ETCD 介绍
概念: 高可用的分布式key-value存储,实现配置共享和服务发现
类似项目: zookeeper和consul
开发语言: Go
接口: 提供restful的http接口,使用简单
实现算法: 基于raft算法的强一致性,高可用的服务存储目录
ETCD的应用场景
服务发现和注册
配置中心
分布式锁
master选举
下载及安装
https://github.com/etcd-io/etcd/releases/tag/v3.5.0
wget tar -xvzf etcd-v3.5.0-linux-amd64.tar.gz cd etcd-v3.5.0-linux-amd64 #查看版本信息 ./etcd --version etcd Version: 3.5.0 Git SHA: 946a5a6f2 Go Version: go1.16.3 Go OS/Arch: linux/amd64 ./etcdctl version etcdctl version: 3.5.0 API version: 3.5 ./etcdutl version etcdutl version: 3.5.0 API version: 3.5
启动
./etcd
默认会在2379端口监听客户端通信,在2380端口监听节点间通信
简单CRUD使用
put
./etcdctl --endpoints=localhost:2379 put foo bar
get 语法:
./etcdctl get [options] <key> [range_end] [flags]
常用参数如下所示:
参数 功能描述
–hex 以十六进制形式输出
–limit number 设置输出结果的最大值
–prefix 根据prefix进行匹配key
–order 对输出结果进行排序,ASCEND 或 DESCEND
–sort-by 按给定字段排序,CREATE, KEY, MODIFY, VALUE, VERSION
–print-value-only 仅输出value值
–from-key 按byte进行比较,获取大于等于指定key的结果
–keys-only 仅获取keys
# 获取键值 # ./etcdctl --endpoints=localhost:2379 get foo # 只获取值 # ./etcdctl get location --print-value-only -beijing # 批量取从foo1到foo3的值,不包括foo3 # ./etcdctl get foo foo3 --print-value-only bar1 bar2 # 批量获取前缀为foo的值 # ./etcdctl get --prefix foo --print-value-only bar1 bar2 bar3 # 批量获取符合前缀的前两个值 # ./etcdctl get --prefix --limit=2 foo --print-value-only bar1 bar2 # 批量获取前缀为foo的值,并排序 # ./etcdctl get --prefix foo --print-value-only --order DESCEND bar3 bar2 bar1
watch
./etcdctl --endpoints=localhost:2379 watch foo
del
./etcdctl --endpoints=localhost:2379 del foo
golang安装etcd/clientv3包
go get go.etcd.io/etcd/clientv3
go实现watch功能
package main import ( "context" "fmt" "go.etcd.io/etcd/clientv3" "time" ) func main() { client,err := clientv3.New(clientv3.Config{ Endpoints: []string{"192.168.56.11:2379"}, DialTimeout: time.Second*3, }) defer client.Close() fmt.Printf("conn succn") for { resultChan := client.Watch(context.Background(),"/logagent/conf") for v := range resultChan{ if v.Err() != nil { fmt.Printf("watch faild,err:%vn",err) continue } for _,e := range v.Events { fmt.Printf("event_type:%v,key:%v,val:%vn",e.Type,e.Kv.Key,string(e.Kv.Value)) } } } }
go 实现put功能
package main import ( "context" "fmt" "go.etcd.io/etcd/clientv3" "time" ) func main() { client,err := clientv3.New(clientv3.Config{ Endpoints: []string{"192.168.56.11:2379"}, DialTimeout: time.Second*3, }) defer client.Close() fmt.Printf("conn succn") _,err = client.Put(context.Background(),"/logagent/conf","sddadas") if err != nil { fmt.Printf("Put faild,err:%vn",err) } }
更多go操作etcd的例子参考:
https://117.119.65.11:10064/?id=1559
- 本文固定链接: https://117.119.65.11:10064/?id=2962
- 转载请注明: admin 于 PHP面试网 发表
《本文》有 0 条评论