fix: watch failure caused instance list not to be updated

fix/consul-watch-failed
baozhecheng 1 year ago
parent bffc1a0989
commit 496f663424
  1. 16
      contrib/registry/consul/client.go
  2. 11
      contrib/registry/consul/registry.go

@ -41,6 +41,8 @@ type Client struct {
deregisterCriticalServiceAfter int deregisterCriticalServiceAfter int
// serviceChecks user custom checks // serviceChecks user custom checks
serviceChecks api.AgentServiceChecks serviceChecks api.AgentServiceChecks
// reRegistry re-registry when service is deregistered
reRegistry bool
} }
func defaultResolver(_ context.Context, entries []*api.ServiceEntry) []*registry.ServiceInstance { 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") err = c.cli.Agent().UpdateTTL("service:"+svc.ID, "pass", "pass")
if err != nil { if err != nil {
log.Errorf("[Consul] update ttl heartbeat to consul failed! err=%v", err) log.Errorf("[Consul] update ttl heartbeat to consul failed! err=%v", err)
// when the previous report fails, try to re register the service if c.reRegistry {
time.Sleep(time.Duration(rand.Intn(5)) * time.Second) // when the previous report fails, try to re register the service
if err := c.cli.Agent().ServiceRegister(asr); err != nil { time.Sleep(time.Duration(rand.Intn(5)) * time.Second)
log.Errorf("[Consul] re registry service failed!, err=%v", err) if err := c.cli.Agent().ServiceRegister(asr); err != nil {
} else { log.Errorf("[Consul] re registry service failed!, err=%v", err)
log.Warn("[Consul] re registry of service occurred success") } else {
log.Warn("[Consul] re registry of service occurred success")
}
} }
} }
} }

@ -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 // Config is consul registry config
type Config struct { type Config struct {
*api.Config *api.Config
@ -190,7 +197,6 @@ func (r *Registry) Watch(ctx context.Context, name string) (registry.Watcher, er
services: &atomic.Value{}, services: &atomic.Value{},
serviceName: name, serviceName: name,
} }
r.registry[name] = set
} }
// init watcher // init watcher
@ -215,6 +221,9 @@ func (r *Registry) Watch(ctx context.Context, name string) (registry.Watcher, er
return nil, err return nil, err
} }
} }
r.registry[name] = set
return w, nil return w, nil
} }

Loading…
Cancel
Save