From 413cc77f7dee1a2f41858736bdf6ef1b9d0a3cab Mon Sep 17 00:00:00 2001 From: xiaoxiaodek <1252930010@qq.com> Date: Thu, 9 Dec 2021 23:27:17 +0800 Subject: [PATCH] fix(config): apollo close function: useless infinite loop causes high cpu usage (#1674) Co-authored-by: wangshaosen --- contrib/config/apollo/watcher.go | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/contrib/config/apollo/watcher.go b/contrib/config/apollo/watcher.go index b1eea6a31..c36d30046 100644 --- a/contrib/config/apollo/watcher.go +++ b/contrib/config/apollo/watcher.go @@ -1,6 +1,7 @@ package apollo import ( + "context" "fmt" "github.com/go-kratos/kratos/v2/config" @@ -66,11 +67,13 @@ func newWatcher(a *apollo, logger log.Logger) (config.Watcher, error) { } changeCh := make(chan []*config.KeyValue) - a.client.AddChangeListener(&customChangeListener{in: changeCh, logger: logger}) + listener := &customChangeListener{in: changeCh, logger: logger} + a.client.AddChangeListener(listener) return &watcher{ out: changeCh, cancelFn: func() { + a.client.RemoveChangeListener(listener) close(changeCh) }, }, nil @@ -78,7 +81,11 @@ func newWatcher(a *apollo, logger log.Logger) (config.Watcher, error) { // Next will be blocked until the Stop method is called func (w *watcher) Next() ([]*config.KeyValue, error) { - return <-w.out, nil + kv, ok := <-w.out + if !ok { + return nil, context.Canceled + } + return kv, nil } func (w *watcher) Stop() error {