增加监听一次key变化的处理
This commit is contained in:
@ -9,6 +9,8 @@ package etcd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"math"
|
||||
"time"
|
||||
)
|
||||
|
||||
// WatchKey 监听key的变化
|
||||
@ -66,3 +68,39 @@ func WatchKeyWithCancel(ctx context.Context, watchKey string, callbackFunc Watch
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// WatchKeyOnce 监听一次key
|
||||
//
|
||||
// timeout 若 <= 0 , 则会一直等待当前key发生变化为止
|
||||
//
|
||||
// timeout 若 > 0 , 则在制定时间内为监听到变化, 立即自动取消,
|
||||
//
|
||||
// Author : go_developer@163.com<白茶清欢>
|
||||
//
|
||||
// Date : 4:35 下午 2021/11/23
|
||||
func WatchKeyOnce(ctx context.Context, watchKey string, callbackFunc WatcherHandler, timeout time.Duration, timeoutHandler TimeoutWatcherHandler) {
|
||||
if nil == callbackFunc {
|
||||
// 变化之后,没有任何逻辑处理,视为不需要监听变化
|
||||
return
|
||||
}
|
||||
|
||||
if timeout == 0 {
|
||||
// 不指定超时时间,默认设置成int64最大值
|
||||
timeout = math.MaxInt16 * time.Second
|
||||
}
|
||||
|
||||
if nil == ctx {
|
||||
ctx = context.Background()
|
||||
}
|
||||
rch := Client.Watch(ctx, watchKey) // <-chan WatchResponse
|
||||
select {
|
||||
case <-time.After(timeout):
|
||||
if nil != timeoutHandler {
|
||||
timeoutHandler(watchKey, timeout)
|
||||
}
|
||||
case watchResp := <-rch:
|
||||
for _, ev := range watchResp.Events {
|
||||
callbackFunc(ev)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user