diff --git a/contrib/registry/consul/client.go b/contrib/registry/consul/client.go index ea5fe846d..a971623c6 100644 --- a/contrib/registry/consul/client.go +++ b/contrib/registry/consul/client.go @@ -41,6 +41,8 @@ type Client struct { deregisterCriticalServiceAfter int // serviceChecks user custom checks serviceChecks api.AgentServiceChecks + // reRegistry re-registry when service is deregistered + reRegistry bool } func defaultResolver(_ context.Context, entries []*api.ServiceEntry) []*registry.ServiceInstance { @@ -223,12 +225,14 @@ func (c *Client) Register(_ context.Context, svc *registry.ServiceInstance, enab err = c.cli.Agent().UpdateTTL("service:"+svc.ID, "pass", "pass") if err != nil { log.Errorf("[Consul] update ttl heartbeat to consul failed! err=%v", err) - // when the previous report fails, try to re register the service - time.Sleep(time.Duration(rand.Intn(5)) * time.Second) - if err := c.cli.Agent().ServiceRegister(asr); err != nil { - log.Errorf("[Consul] re registry service failed!, err=%v", err) - } else { - log.Warn("[Consul] re registry of service occurred success") + if c.reRegistry { + // when the previous report fails, try to re register the service + time.Sleep(time.Duration(rand.Intn(5)) * time.Second) + if err := c.cli.Agent().ServiceRegister(asr); err != nil { + log.Errorf("[Consul] re registry service failed!, err=%v", err) + } else { + log.Warn("[Consul] re registry of service occurred success") + } } } } diff --git a/contrib/registry/consul/registry.go b/contrib/registry/consul/registry.go index 8105ab1d0..1fe8ace45 100644 --- a/contrib/registry/consul/registry.go +++ b/contrib/registry/consul/registry.go @@ -86,6 +86,13 @@ func WithServiceCheck(checks ...*api.AgentServiceCheck) Option { } } +// WithReRegistry re-registry when service is deregistered +func WithReRegistry() Option { + return func(r *Registry) { + r.cli.reRegistry = true + } +} + // Config is consul registry config type Config struct { *api.Config @@ -190,7 +197,6 @@ func (r *Registry) Watch(ctx context.Context, name string) (registry.Watcher, er services: &atomic.Value{}, serviceName: name, } - r.registry[name] = set } // init watcher @@ -215,6 +221,9 @@ func (r *Registry) Watch(ctx context.Context, name string) (registry.Watcher, er return nil, err } } + + r.registry[name] = set + return w, nil }