fix:etcd get&watch not atomic (#2321)

This commit is contained in:
maizige
2022-08-29 08:35:31 +08:00
committed by GitHub
parent dfeef5e497
commit 422f401153
2 changed files with 22 additions and 12 deletions

View File

@@ -208,7 +208,7 @@ func (c *cluster) handleWatchEvents(key string, events []*clientv3.Event) {
}
}
func (c *cluster) load(cli EtcdClient, key string) {
func (c *cluster) load(cli EtcdClient, key string) int64 {
var resp *clientv3.GetResponse
for {
var err error
@@ -232,6 +232,8 @@ func (c *cluster) load(cli EtcdClient, key string) {
}
c.handleChanges(key, kvs)
return resp.Header.Revision
}
func (c *cluster) monitor(key string, l UpdateListener) error {
@@ -244,9 +246,9 @@ func (c *cluster) monitor(key string, l UpdateListener) error {
return err
}
c.load(cli, key)
rev := c.load(cli, key)
c.watchGroup.Run(func() {
c.watch(cli, key)
c.watch(cli, key, rev)
})
return nil
@@ -278,22 +280,28 @@ func (c *cluster) reload(cli EtcdClient) {
for _, key := range keys {
k := key
c.watchGroup.Run(func() {
c.load(cli, k)
c.watch(cli, k)
rev := c.load(cli, k)
c.watch(cli, k, rev)
})
}
}
func (c *cluster) watch(cli EtcdClient, key string) {
func (c *cluster) watch(cli EtcdClient, key string, rev int64) {
for {
if c.watchStream(cli, key) {
if c.watchStream(cli, key, rev) {
return
}
}
}
func (c *cluster) watchStream(cli EtcdClient, key string) bool {
rch := cli.Watch(clientv3.WithRequireLeader(c.context(cli)), makeKeyPrefix(key), clientv3.WithPrefix())
func (c *cluster) watchStream(cli EtcdClient, key string, rev int64) bool {
var rch clientv3.WatchChan
if rev != 0 {
rch = cli.Watch(clientv3.WithRequireLeader(c.context(cli)), makeKeyPrefix(key), clientv3.WithPrefix(), clientv3.WithRev(rev+1))
} else {
rch = cli.Watch(clientv3.WithRequireLeader(c.context(cli)), makeKeyPrefix(key), clientv3.WithPrefix())
}
for {
select {
case wresp, ok := <-rch: