From 1b1dad53564b84f7aaad3f38923def7e7b15444f Mon Sep 17 00:00:00 2001 From: xujp <1240402516@qq.com> Date: Fri, 25 Dec 2020 11:43:35 +0800 Subject: [PATCH] fix(discovery):Fix the protected data race --- discovery/discovery.go | 4 ++++ discovery/syncup.go | 7 ++++++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/discovery/discovery.go b/discovery/discovery.go index acfafe9..156bd6a 100644 --- a/discovery/discovery.go +++ b/discovery/discovery.go @@ -2,6 +2,7 @@ package discovery import ( "context" + "sync" "sync/atomic" "time" @@ -17,6 +18,7 @@ type Discovery struct { client *http.Client registry *registry.Registry nodes atomic.Value + lock sync.RWMutex } // New get a discovery. @@ -38,5 +40,7 @@ func New(c *conf.Config) (d *Discovery, cancel context.CancelFunc) { func (d *Discovery) exitProtect() { // exist protect mode after two renew cycle time.Sleep(time.Second * 60) + d.lock.Lock() d.protected = false + d.lock.Unlock() } diff --git a/discovery/syncup.go b/discovery/syncup.go index eeb4d08..1e08179 100644 --- a/discovery/syncup.go +++ b/discovery/syncup.go @@ -21,7 +21,10 @@ var ( // if service in init protect mode,only support write, // read operator isn't supported. func (d *Discovery) Protected() bool { - return d.protected + d.lock.RLock() + protected := d.protected + d.lock.RUnlock() + return protected } // syncUp populates the registry information from a peer eureka node. @@ -45,7 +48,9 @@ func (d *Discovery) syncUp() { continue } // sync success from other node,exit protected mode + d.lock.Lock() d.protected = false + d.lock.Unlock() for _, is := range res.Data { for _, i := range is { _ = d.registry.Register(i, i.LatestTimestamp)