Skip to content

Commit

Permalink
fix issue 3100
Browse files Browse the repository at this point in the history
  • Loading branch information
joy999 committed Oct 27, 2023
1 parent 3ea61d0 commit 9a2dfe6
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 21 deletions.
21 changes: 5 additions & 16 deletions contrib/registry/nacos/nacos_watcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,23 +38,12 @@ func newWatcher(ctx context.Context) *Watcher {
// Proceed proceeds watch in blocking way.
// It returns all complete services that watched by `key` if any change.
func (w *Watcher) Proceed() (services []gsvc.Service, err error) {
n := len(w.event)
servicesMap := map[string]gsvc.Service{}
for i := 0; i < n; i++ {
e := <-w.event
if e.Err != nil {
err = e.Err
return
}
newServices := NewServicesFromInstances(e.Services)
for _, s := range newServices {
servicesMap[s.GetName()] = s
}
}
services = make([]gsvc.Service, 0, len(servicesMap))
for _, s := range servicesMap {
services = append(services, s)
e := <-w.event
if e.Err != nil {
err = e.Err
return
}
services = NewServicesFromInstances(e.Services)
return
}

Expand Down
22 changes: 17 additions & 5 deletions contrib/registry/nacos/nacos_z_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,13 @@
package nacos_test

import (
"context"
"sync/atomic"
"testing"
"time"

"github.com/gogf/gf/contrib/registry/nacos/v2"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/net/gsvc"
"github.com/gogf/gf/v2/os/gctx"
"github.com/gogf/gf/v2/test/gtest"
Expand Down Expand Up @@ -121,9 +124,19 @@ func TestWatch(t *testing.T) {
})

gtest.C(t, func(t *gtest.T) {
ctx := gctx.New()
watcher, err := registry.Watch(ctx, svc1.GetPrefix())
t.AssertNil(err)

var latestProceedResult atomic.Value
g.Go(ctx, func(ctx context.Context) {
res, err := watcher.Proceed()
t.AssertNil(err)
latestProceedResult.Store(res)
}, func(ctx context.Context, exception error) {
t.Fatal(exception)
})

// Register another service.
svc2 := &gsvc.LocalService{
Name: svc1.Name,
Expand All @@ -140,9 +153,8 @@ func TestWatch(t *testing.T) {

// Watch and retrieve the service changes:
// svc1 and svc2 is the same service name, which has 2 endpoints.
proceedResult, err := watcher.Proceed()

t.AssertNil(err)
proceedResult, ok := latestProceedResult.Load().([]gsvc.Service)
t.Assert(ok, true)
t.Assert(len(proceedResult), 1)
t.Assert(
sortEndpoints(proceedResult[0].GetEndpoints()),
Expand All @@ -155,8 +167,8 @@ func TestWatch(t *testing.T) {
t.AssertNil(err)

time.Sleep(time.Second * 10)
proceedResult, err = watcher.Proceed()
t.AssertNil(err)
proceedResult, ok = latestProceedResult.Load().([]gsvc.Service)
t.Assert(ok, true)
t.Assert(len(proceedResult), 1)
t.Assert(
sortEndpoints(proceedResult[0].GetEndpoints()),
Expand Down

0 comments on commit 9a2dfe6

Please sign in to comment.