github.com/kaydxh/golang@v0.0.131/pkg/discovery/etcd/etcd.watch.go (about)

     1  package etcd
     2  
     3  import (
     4  	"context"
     5  
     6  	"go.etcd.io/etcd/api/v3/mvccpb"
     7  	clientv3 "go.etcd.io/etcd/client/v3"
     8  )
     9  
    10  func Watch(ctx context.Context, kv *clientv3.Client, key string, createCallbackFunc, deleteCallbackFunc EventCallbackFunc) {
    11  	ch := kv.Watch(ctx, key, clientv3.WithPrefix(), clientv3.WithCreatedNotify())
    12  	go func() error {
    13  		for resp := range ch {
    14  			for _, event := range resp.Events {
    15  				switch event.Type {
    16  				case mvccpb.PUT:
    17  					if createCallbackFunc != nil {
    18  						createCallbackFunc(ctx, string(event.Kv.Key), string(event.Kv.Value))
    19  					}
    20  				case mvccpb.DELETE:
    21  					if deleteCallbackFunc != nil {
    22  						deleteCallbackFunc(ctx, string(event.Kv.Key), string(event.Kv.Value))
    23  
    24  					}
    25  				}
    26  			}
    27  		}
    28  
    29  		return nil
    30  	}()
    31  
    32  	return
    33  }