diff --git a/middleware/etcd/define.go b/middleware/etcd/define.go index f2f73fa..b2f3d00 100644 --- a/middleware/etcd/define.go +++ b/middleware/etcd/define.go @@ -10,6 +10,8 @@ package etcd import ( "math" "time" + + "go.etcd.io/etcd/clientv3" ) // 初始化client各种默认配置 @@ -33,3 +35,6 @@ const ( // DefaultGetTimeout get 默认超时时间 DefaultGetTimeout = time.Second ) + +// WatcherHandler 监听key变化的处理函数 +type WatcherHandler func(event *clientv3.Event) diff --git a/middleware/etcd/watch.go b/middleware/etcd/watch.go new file mode 100644 index 0000000..c48605a --- /dev/null +++ b/middleware/etcd/watch.go @@ -0,0 +1,30 @@ +// Package etcd... +// +// Description : 监听key的变化 +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 2021-11-23 2:58 下午 +package etcd + +import ( + "context" +) + +// WatchKey 监听key的变化 +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 2:58 下午 2021/11/23 +func WatchKey(ctx context.Context, watchKey string, callbackFunc WatcherHandler) { + if nil == callbackFunc { + // 变化之后,没有任何逻辑处理,视为不需要监听变化 + return + } + rch := Client.Watch(context.Background(), watchKey) // <-chan WatchResponse + for watchResp := range rch { + for _, ev := range watchResp.Events { + callbackFunc(ev) + } + } +}