新版本etcd已经改为:
main.go
import clientv3 "go.etcd.io/etcd/client/v3"
go.mod:
go 1.23.3
require go.etcd.io/etcd/client/v3 v3.5.17
参考最新的官方文档:
https://github.com/etcd-io/etcd/blob/main/client/v3/README.md
etcd/clientv3
is the official Go etcd client for v3.
Install
go get go.etcd.io/etcd/client/v3
Get started
Create client using clientv3.New
:
import clientv3 "go.etcd.io/etcd/client/v3" func main() { cli, err := clientv3.New(clientv3.Config{ Endpoints: []string{"localhost:2379", "localhost:22379", "localhost:32379"}, DialTimeout: 5 * time.Second, }) if err != nil { // handle error! } defer cli.Close() }
etcd v3 uses gRPC for remote procedure calls. And clientv3
uses grpc-go to connect to etcd. Make sure to close the client after using it. If the client is not closed, the connection will have leaky goroutines. To specify client request timeout, pass context.WithTimeout
to APIs:
ctx, cancel := context.WithTimeout(context.Background(), timeout) resp, err := cli.Put(ctx, "sample_key", "sample_value") cancel() if err != nil { // handle error! } // use the response
For full compatibility, it is recommended to install released versions of clients using go modules.