2021-11-23 15:13:50 +08:00
|
|
|
// 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
|
|
|
|
}
|
2021-11-23 16:31:25 +08:00
|
|
|
if nil == ctx {
|
|
|
|
ctx = context.Background()
|
|
|
|
}
|
|
|
|
rch := Client.Watch(ctx, watchKey) // <-chan WatchResponse
|
2021-11-23 15:13:50 +08:00
|
|
|
for watchResp := range rch {
|
|
|
|
for _, ev := range watchResp.Events {
|
|
|
|
callbackFunc(ev)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2021-11-23 16:31:25 +08:00
|
|
|
|
|
|
|
// WatchKeyWithCancel 可以随时取消的
|
|
|
|
//
|
|
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
|
|
//
|
|
|
|
// Date : 3:16 下午 2021/11/23
|
|
|
|
func WatchKeyWithCancel(ctx context.Context, watchKey string, callbackFunc WatcherHandler, cancelChan chan interface{}, cancelDealFunc CancelWatcherHandler) {
|
|
|
|
if nil == callbackFunc {
|
|
|
|
// 变化之后,没有任何逻辑处理,视为不需要监听变化
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if nil == ctx {
|
|
|
|
ctx = context.Background()
|
|
|
|
}
|
|
|
|
|
|
|
|
rch := Client.Watch(context.Background(), watchKey) // <-chan WatchResponse
|
|
|
|
|
|
|
|
hasFinish := false
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case cancelData := <-cancelChan:
|
|
|
|
if nil != cancelDealFunc {
|
|
|
|
cancelDealFunc(watchKey, cancelData)
|
|
|
|
}
|
|
|
|
hasFinish = true
|
|
|
|
case watchResp := <-rch:
|
|
|
|
for _, ev := range watchResp.Events {
|
|
|
|
callbackFunc(ev)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if hasFinish {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|