@@ -24,6 +24,8 @@ type consulRegistry struct {
2424
2525 sync.Mutex
2626 register map [string ]uint64
27+ // lastChecked tracks when a node was last checked as existing in Consul
28+ lastChecked map [string ]time.Time
2729}
2830
2931func getDeregisterTTL (t time.Duration ) time.Duration {
@@ -118,8 +120,9 @@ func configure(c *consulRegistry, opts ...Option) {
118120
119121func newConsulRegistry (opts ... Option ) Registry {
120122 cr := & consulRegistry {
121- opts : Options {},
122- register : make (map [string ]uint64 ),
123+ opts : Options {},
124+ register : make (map [string ]uint64 ),
125+ lastChecked : make (map [string ]time.Time ),
123126 }
124127 configure (cr , opts ... )
125128 return cr
@@ -135,9 +138,10 @@ func (c *consulRegistry) Deregister(s *Service) error {
135138 return errors .New ("Require at least one node" )
136139 }
137140
138- // delete our hash of the service
141+ // delete our hash and time check of the service
139142 c .Lock ()
140143 delete (c .register , s .Name )
144+ delete (c .lastChecked , s .Name )
141145 c .Unlock ()
142146
143147 node := s .Nodes [0 ]
@@ -181,7 +185,13 @@ func (c *consulRegistry) Register(s *Service, opts ...RegisterOption) error {
181185 // if it's already registered and matches then just pass the check
182186 if ok && v == h {
183187 if options .TTL == time .Duration (0 ) {
184- services , _ , err := c .Client .Health ().Checks (s .Name , nil )
188+ // ensure that our service hasn't been deregistered by Consul
189+ if time .Since (c .lastChecked [s .Name ]) <= getDeregisterTTL (regInterval ) {
190+ return nil
191+ }
192+ services , _ , err := c .Client .Health ().Checks (s .Name , & consul.QueryOptions {
193+ AllowStale : true ,
194+ })
185195 if err == nil {
186196 for _ , v := range services {
187197 if v .ServiceID == node .Id {
@@ -245,9 +255,10 @@ func (c *consulRegistry) Register(s *Service, opts ...RegisterOption) error {
245255 return err
246256 }
247257
248- // save our hash of the service
258+ // save our hash and time check of the service
249259 c .Lock ()
250260 c .register [s .Name ] = h
261+ c .lastChecked [s .Name ] = time .Now ()
251262 c .Unlock ()
252263
253264 // if the TTL is 0 we don't mess with the checks
0 commit comments