Created
April 10, 2023 23:58
-
-
Save mattrasband/a63e38a142c676c6922187a03466aa77 to your computer and use it in GitHub Desktop.
etcd watcher with previous values included in updates
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"log" | |
"time" | |
"github.com/google/uuid" | |
etcd "go.etcd.io/etcd/client/v3" | |
) | |
func main() { | |
client, err := etcd.New(etcd.Config{ | |
Endpoints: []string{"127.0.0.1:2379"}, | |
DialTimeout: 5 * time.Second, | |
}) | |
if err != nil { | |
log.Fatal(err) | |
} | |
key := uuid.NewString() | |
val := uuid.NewString() | |
v, err := client.Put(context.Background(), key, val) | |
if err != nil { | |
log.Fatalf("unable to put: %s", err) | |
} | |
w := client.Watch(context.Background(), key) | |
go func() { | |
for v := range w { | |
log.Printf("new value: %s", v.Events[0].Kv.Value) | |
} | |
}() | |
// v, err := client.Get(context.Background(), key) | |
// if err != nil { | |
// log.Fatalf("unable to get: %s", err) | |
// } | |
// log.Printf("v: version: %d; value: %s", v.Kvs[0].Version, v.Kvs[0].Value) | |
log.Printf("tx: %+v", v.OpResponse()) | |
newVal := uuid.NewString() | |
tx, err := client.Txn(context.Background()). | |
If(etcd.Compare(etcd.Value(key), "!=", newVal)). | |
Then(etcd.OpPut(key, newVal, etcd.WithPrevKV())). | |
Else(etcd.OpGet(key)). | |
Commit() | |
if err != nil { | |
log.Fatalf("unable to commit: %s", err) | |
} | |
log.Printf("old: %s; new: %s", tx.Responses[0].GetResponsePut().PrevKv.Value, newVal) | |
tx, err = client.Txn(context.Background()). | |
If(etcd.Compare(etcd.Value(key), "!=", newVal)). | |
Then(etcd.OpPut(key, newVal, etcd.WithPrevKV())). | |
Else(etcd.OpGet(key, etcd.WithFirstKey()...)). | |
Commit() | |
if err != nil { | |
log.Fatalf("unable to commit: %s", err) | |
} | |
log.Printf("should be same: %s", tx.Responses[0].GetResponseRange().Kvs[0].Value) | |
// if _, err := client.Put(context.Background(), key, "foo"); err != nil { | |
// log.Fatalf("unable to put: %s", err) | |
// } | |
time.Sleep(time.Second * 5) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment