修复watcher取消后,监听协程仍在的问题

This commit is contained in:
白茶清欢 2021-11-24 00:11:14 +08:00
parent c21e16138d
commit 7bef73334c

View File

@ -13,7 +13,7 @@ import (
"time"
)
// WatchKey 监听key的变化
// WatchKey 监听key的变化,永久监听
//
// Author : go_developer@163.com<白茶清欢>
//
@ -26,6 +26,7 @@ func WatchKey(ctx context.Context, watchKey string, callbackFunc WatcherHandler)
if nil == ctx {
ctx = context.Background()
}
rch := Client.Watch(ctx, watchKey) // <-chan WatchResponse
for watchResp := range rch {
for _, ev := range watchResp.Events {
@ -47,6 +48,11 @@ func WatchKeyWithCancel(ctx context.Context, watchKey string, callbackFunc Watch
if nil == ctx {
ctx = context.Background()
}
var (
cancelFunc context.CancelFunc
)
ctx, cancelFunc = context.WithCancel(ctx)
defer cancelFunc()
rch := Client.Watch(context.Background(), watchKey) // <-chan WatchResponse
@ -92,6 +98,11 @@ func WatchKeyOnce(ctx context.Context, watchKey string, callbackFunc WatcherHand
if nil == ctx {
ctx = context.Background()
}
var (
cancelFunc context.CancelFunc
)
ctx, cancelFunc = context.WithCancel(ctx)
defer cancelFunc()
rch := Client.Watch(ctx, watchKey) // <-chan WatchResponse
select {
case <-time.After(timeout):