test.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. clientv3 "go.etcd.io/etcd/client/v3"
  6. "time"
  7. )
  8. func main() {
  9. cli, err := clientv3.New(clientv3.Config{
  10. Endpoints: []string{"106.54.33.152:2379"},
  11. DialTimeout: 5 * time.Second,
  12. })
  13. if err != nil {
  14. panic(err)
  15. }
  16. defer cli.Close()
  17. ctx, cancel := context.WithCancel(context.Background())
  18. defer cancel()
  19. _, err = cli.Put(ctx, "/services/service", "running")
  20. if err != nil {
  21. fmt.Printf("Failed to put service instance: %v\n", err)
  22. return
  23. }
  24. go func() {
  25. time.Sleep(time.Second * 5)
  26. commit, err := cli.Txn(ctx).
  27. If(clientv3.Compare(clientv3.Value("/services/service"), "=", "running")).
  28. Then(clientv3.OpPut("/services/service", "stop")).
  29. Else(clientv3.OpPut("/services/service", "error")).
  30. Commit()
  31. if err != nil {
  32. fmt.Printf("Failed to commit transaction: %v\n", err)
  33. return
  34. }
  35. if !commit.Succeeded {
  36. fmt.Printf("Transaction failed\n")
  37. }
  38. fmt.Println(commit)
  39. }()
  40. _, err = cli.Put(ctx, "/services/service", "running1")
  41. if err != nil {
  42. fmt.Printf("Failed to put service instance: %v\n", err)
  43. return
  44. }
  45. time.Sleep(time.Second * 10)
  46. }