gitee.com/h79/goutils@v1.22.10/discovery/etcd/watcher.go (about)

     1  package etcd
     2  
     3  import (
     4  	"context"
     5  	"gitee.com/h79/goutils/common/system"
     6  	"gitee.com/h79/goutils/discovery/service"
     7  	"gitee.com/h79/goutils/discovery/watch"
     8  	"go.etcd.io/etcd/api/v3/mvccpb"
     9  	clientv3 "go.etcd.io/etcd/client/v3"
    10  )
    11  
    12  type Watcher struct {
    13  	client *clientv3.Client
    14  	wc     watch.Chan
    15  	ctx    context.Context
    16  	cancel context.CancelFunc
    17  }
    18  
    19  func NewWatcher(client *clientv3.Client, sizeChan int) *Watcher {
    20  	ctx, cancel := context.WithCancel(context.Background())
    21  	return &Watcher{
    22  		client: client,
    23  		wc:     make(watch.Chan, sizeChan),
    24  		cancel: cancel,
    25  		ctx:    ctx,
    26  	}
    27  }
    28  
    29  func (watcher *Watcher) Watch(key watch.Key) (watch.Chan, error) {
    30  	wc := watcher.client.Watch(context.Background(), key.ToKey(), clientv3.WithPrefix())
    31  	system.ChildRunning(func() {
    32  		select {
    33  		case resp := <-wc:
    34  			for _, ev := range resp.Events {
    35  				data := service.Data{Key: service.NewKey(string(ev.Kv.Key)), Value: string(ev.Kv.Value)}
    36  				switch ev.Type {
    37  				case mvccpb.PUT:
    38  					watcher.wc <- watch.NewChanged(data, watch.Put)
    39  
    40  				case mvccpb.DELETE:
    41  					watcher.wc <- watch.NewChanged(data, watch.Delete)
    42  				}
    43  			}
    44  		case <-watcher.ctx.Done():
    45  			return
    46  
    47  		case <-system.Closed():
    48  			return
    49  		}
    50  	})
    51  	return watcher.wc, nil
    52  }
    53  
    54  func (watcher *Watcher) Changed(cmd watch.Changed) {
    55  	watcher.wc <- cmd
    56  }
    57  
    58  func (watcher *Watcher) Stop() error {
    59  	watcher.cancel()
    60  	return nil
    61  }