github.com/aaabigfish/gopkg@v1.1.0/etcdv3/registrar.go (about) 1 package etcdv3 2 3 import ( 4 "sync" 5 "time" 6 7 "github.com/aaabigfish/gopkg/log" 8 ) 9 10 // Registrar registers service instance liveness information to etcd. 11 type Registrar struct { 12 client Client 13 service Service 14 15 quitmtx sync.Mutex 16 checkServ chan struct{} 17 quit chan struct{} 18 } 19 20 // NewRegistrar returns a etcd Registrar acting on the provided catalog 21 // registration (service). 22 func NewRegistrar(client Client, service Service) *Registrar { 23 return &Registrar{ 24 client: client, 25 service: service, 26 checkServ: make(chan struct{}, 1), 27 } 28 } 29 30 // Register implements the sd.Registrar interface. Call it when you want your 31 // service to be registered in etcd, typically at startup. 32 func (r *Registrar) Register() error { 33 if err := r.client.Register(r.service, r.checkServ); err != nil { 34 log.Errorf("Register(%+v) err(%v)", r, err) 35 return err 36 } 37 if r.service.TTL != nil { 38 log.Warnf("Register action lease(%+v)", r.client.LeaseID()) 39 } 40 41 go r.AutoCheckService() 42 return nil 43 } 44 45 func (r *Registrar) AutoCheckService() { 46 for { 47 select { 48 case <-r.checkServ: 49 log.Warn("AutoCheckService repeat register") 50 err := r.Register() 51 if err != nil { 52 time.AfterFunc(3*time.Second, func() { 53 r.checkServ <- struct{}{} 54 }) 55 } 56 } 57 } 58 } 59 60 // Deregister implements the sd.Registrar interface. Call it when you want your 61 // service to be deregistered from etcd, typically just prior to shutdown. 62 func (r *Registrar) Deregister() { 63 if err := r.client.Deregister(r.service); err != nil { 64 log.Errorf("Deregister(%+v) err(%v)", r.service, err) 65 } else { 66 log.Info("action deregister") 67 } 68 69 r.quitmtx.Lock() 70 defer r.quitmtx.Unlock() 71 if r.quit != nil { 72 close(r.quit) 73 r.quit = nil 74 } 75 }