How to use etcd in golang

王林
Release: 2023-05-10 09:24:36
Original
1174 people have browsed it

In distributed systems, configuration management is a very critical link. etcd is a highly available, distributed, and consistent key-value storage container that is often used in scenarios such as distributed coordination, service discovery, and configuration management. Golang is a compiled language. Because of its efficient performance and concurrency features, it has become the best choice for using etcd. This article will introduce how golang uses etcd.

  1. Install etcd

Download the version that matches the system on the official website https://github.com/etcd-io/etcd/releases, unzip it and run etcd .

  1. Install etcd client library
go get go.etcd.io/etcd/clientv3
Copy after login
  1. Connect etcd

The way to connect etcd in golang is provided by etcd Implemented by clientv3 library. The following is a simple example of connecting etcd:

import (
    "context"
    "fmt"
    "go.etcd.io/etcd/clientv3"
)

func main() {
    config := clientv3.Config{
        Endpoints:   []string{"localhost:2379"}, // etcd endpoints
        DialTimeout: 5 * time.Second,
    }
    client, err := clientv3.New(config)
    if err != nil {
        // handle error
    }
    defer client.Close()
}
Copy after login
  1. Writing and reading key-value pairs

Next we can use the Put and Get methods provided by clientv3 to Write and read key-value pairs. The Put method will write a key-value pair to etcd, and the Get method will read the value of the key from etcd. The following is a complete example:

import (
    "context"
    "fmt"
    "go.etcd.io/etcd/clientv3"
)

func main() {
    // 连接etcd
    config := clientv3.Config{
        Endpoints:   []string{"localhost:2379"}, // etcd endpoints
        DialTimeout: 5 * time.Second,
    }
    client, err := clientv3.New(config)
    if err != nil {
        // handle error
    }
    defer client.Close()

    // 写入键值对
    _, err = client.Put(context.Background(), "hello", "world")
    if err != nil {
        // handle error
    }

    // 读取键值对
    resp, err := client.Get(context.Background(), "hello")
    if err != nil {
        // handle error
    }
    // 输出键的值
    for _, ev := range resp.Kvs {
        fmt.Printf("%s : %s
", ev.Key, ev.Value)
    }
}
Copy after login

By running the above example, we can write a key-value pair in etcd and read the value of the key from etcd.

  1. Monitor changes in key-value pairs in etcd

Another powerful function of etcd is that it can realize real-time monitoring of key-value pairs through the Watch mechanism. Once a key If a value pair changes, you will be notified immediately. Clientv3 provides the Watch method, which we can use to monitor changes in a certain key in etcd. The following is a complete example:

import (
    "context"
    "fmt"
    "go.etcd.io/etcd/clientv3"
)

func main() {
    // 连接etcd
    config := clientv3.Config{
        Endpoints:   []string{"localhost:2379"}, // etcd endpoints
        DialTimeout: 5 * time.Second,
    }
    client, err := clientv3.New(config)
    if err != nil {
        // handle error
    }
    defer client.Close()

    ctx, cancel := context.WithCancel(context.Background())
    defer cancel()

    // 监听键值对变化
    rch := client.Watch(ctx, "hello")
    for wresp := range rch {
        for _, ev := range wresp.Events {
            fmt.Printf("%s %q: %q
", ev.Type, ev.Kv.Key, ev.Kv.Value)
        }
    }
}
Copy after login

In this example, we create a context and use the Watch method to monitor the "hello" key in etcd. If the value of a key changes, the Watch method will return a notification containing the changed key-value pair. We can iterate through these notifications and output the corresponding content.

  1. Summary

This article introduces how golang uses etcd, including introduction to connecting etcd, writing and reading key-value pairs, and monitoring changes in key-value pairs. etcd is a very practical distributed key-value storage container. Combined with golang's efficient performance and concurrency features, it can achieve very flexible and efficient configuration management.

The above is the detailed content of How to use etcd in golang. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!