基于go-micro+etcd+gin微服务之服务注册与发现
etcd主要API
1.Put(key,value)/Delete(key)
$ ./bin/etcdctl put foo "Hello World!"
OK
$ ./bin/etcdctl del key
1
2.Get(key)/Get(keyFrom,keyEnd)
//第一种是指定单个 key 的查询,第二种是指定的一个 key 的范围;
./bin/etcdctl put web1 value1
$ ./bin/etcdctl put web2 value2
$ ./bin/etcdctl put web3 value3
$ ./bin/etcdctl get web --prefix //根据前缀查询
web1
value1
web2
value2
web3
value3
3.Watch(key/keyPrefix)
//数据订阅,etcd 提供了 Watch 机制,我们可以利用 watch 实时订阅到 etcd 中增量的数据更新,watch 支持指定单个 key,也可以指定一个 key 的前缀,在实际应用场景中的通常会采用第二种形势
// 当 stock1 的数值改变( put 方法)的时候,watch 会收到通知
$ ./bin/etcdctl watch stock1
// 新打开终端etcd
$ ./bin/etcdctl put stock1 1000
//在watch 终端显示
PUT
stock1
1000
//在watch终端中可以看到以stock为前缀的数值改变
$ ./bin/etcdctl watch stock --prefix
$ ./bin/etcdctl put stock1 10
$ ./bin/etcdctl put stock2 20
PUT
stock1
10
PUT
stock2
20
4.Transactions(if/then/else ops).Commit()
//事务操作。etcd 提供了一个简单的事务支持,用户可以通过指定一组条件满足时执行某些动作,当条件不成立的时候执行另一组操作,类似于代码中的 if else 语句,etcd 确保整个操作的原子性
$ ./bin/etcdctl put user1 bad
OK
$ ./bin/etcdctl txn --interactive
compares:
// 输入以下内容,输入结束按 两次回车
value("user1") = "bad"
//如果 user1 = bad,则执行 get user1
success requests (get, put, del):
get user1
//如果 user1 != bad,则执行 put user1 good
failure requests (get, put, del):
put user1 good
// 运行结果,执行 success
SUCCESS
user1
bad
5.Leases:Grant/Revoke/KeepAlive
//设置访问的限制时间
$ ./bin/etcdctl lease grant 300
# lease 326963a02758b527 granted with TTL(300s)
//维持租约
$ ./bin/etcdctl lease keep-alive 326963a02758b520
//撤销租约
$ ./bin/etcdctl lease revoke 326963a02758b527
lease 326963a02758b527 revoked
客户端
func GetImageCd(ctx *gin.Context) {
uuid := ctx.Param("uuid")
consulService := micro.NewService(
micro.Registry(etcd.NewRegistry(registry.Addrs