This is the 27th day of my participation in the August More Text Challenge

preface

Ectd was introduced in the previous section as a quick start. This article describes how to call its API to perform operations

Etcd supports two versions, V2 and V3. The k8S in use now has used V3, and the latest version of K8S is using V3. The future use will definitely use V3, keep up with the trend

Etcd-v3api address: github.com/etcd-io/etc…

Api-example address: github.com/etcd-io/etc…

API example

A cursory look at some of the etCD Clien source code reveals the following types of client implementations

  • Cluster: Member management
  • KV: k-V key operation
  • Lease: operations related to the Lease. The authorized key will be deleted when the Lease expires
  • Watcher: Watch subscriptions to listen for the latest data changes
  • Auth: Manages etCD users and permissions. This operation is performed by administrators
  • Maintenance: Maintains etCD, state, snapshot, etc

This article will not list all of the above types, but only demonstrate some of them

Creating a Client

Use the editor tool to write code, so you don’t need to download, direct code import, press Alt+Enter to synchronize the package, because this is the go Model management package

This time, instead of using init and var to specify the client, just write a function, whoever needs to use it later, call that function

Create a client

func CreateCli() *clientv3.Client {
   cli, err := clientv3.New(clientv3.Config{
      Endpoints:   []string{"10.10.1.32:2379"},
      DialTimeout: 5 * time.Second,
   })
   iferr ! = nil { log.Fatalln("Etcd connection failed:", err)
   }
   log.Println("Etcd - V3API connection successful")
   return cli
}
Copy the code
  • Close the client after use, otherwise goroutines will leak

Put/Get operation

You can pass the timeout control context.withTimeout to the API when performing data operations

Call the Put and Get methods to set and retrieve a k/v value

func PutGet() {
   cli := CreateCli()

   // Create a 5-second timeout control
   ctx, cancelFunc := context.WithTimeout(context.Background(), time.Second*5000)

   / / Put data
   _, err := cli.Put(ctx, "hello2"."world2")
   cancelFunc()
   iferr ! = nil { log.Println("Put data failed:", err)
   }
   / / Get data
   ctx2, cancelFunc2 := context.WithTimeout(context.Background(), time.Second*5000)
   resp, err := cli.Get(ctx2, "hello2")
   cancelFunc2()
   iferr ! = nil { log.Println("Get data failed:", err)
   }
   for _, v := range resp.Kvs {
      fmt.Println("Get the data is:", v)
   }
   defer cli.Close()
}
Copy the code

Deleting a key is similar to passing CTX and the key name in cli.delete

Watch the operation

Because watch is a monitored operation, it is not sure when the data changes, so there is no need to set timeout control

func watch() {
   cli := CreateCli()

   / / Watch operations
   watch := cli.Watch(context.TODO(), "hello")
   for watchsp := range watch {
      for _, ev := range watchsp.Events {
         log.Println("Value changed:", ev.Type, string(ev.Kv.Key), string(ev.Kv.Value))
      }
   }

   defer cli.Close()
}
Copy the code

Start the service, modify the data, and get a response

etcdctl --endpoints=http:/ / 127.0.0.1:2379 put the hello word3 ""
Copy the code

Lease operation

Etcd leases are controlled by setting a lifetime value. This parameter takes effect when creating a key

func lease() {
   cli := CreateCli()
   // Create a TTL of 30 (lease)
   grant, err := cli.Grant(context.TODO(), 30)
   iferr ! = nil { log.Println(Failed to create lease:, err)
   }
   Test2 key will be deleted after 30 seconds
   _, err = cli.Put(context.TODO(), "test2"."ddd2", clientv3.WithLease(grant.ID))
   iferr ! = nil { log.Println("Create key with lease", err)
   }

   defer cli.Close()
}
Copy the code

KeepAlive operation

In other cases, the TTL of the key needs to be kept at all times. This can be set using keepalive

This key will remain in place until it is deleted when your program exits

func keepalive() {
   cli := CreateCli()
   grant, _ := cli.Grant(context.TODO(), 5)
   _, _ = cli.Put(context.TODO(), "test3"."ddd3", clientv3.WithLease(grant.ID))
   alive, _ := cli.KeepAlive(context.TODO(), grant.ID)
   for {
      a: =<-alive fmt.Println("ttl: ", a.TTL) } defer cli.Close() }Copy the code

State examination (mmse)

This method can not only operate on the cluster status of the client, but also check the status of any specified cluster by replacing the write IP address with the desired IP address

func status() {
   cli := CreateCli()

   for _, ep := range endpoints() {
      status, err := cli.Status(context.TODO(), ep)
      iferr ! = nil { log.Println(err) } fmt.Println("Endpoint:", ep, "State:", status)
   }

   cli.Close()
}

func endpoints() []string {
   return []string{"ip:2379"}}Copy the code

conclusion

Etcd API through the above demo, it can be seen that the use of API is very simple and convenient, it is easy to develop functions

Commonly used API, all in the CLI is inside