go.etcd.io/etcd/client/v3
是 etcd 的官方 Go 语言客户端库
当etcd
未启动时,无法通过设置DialTimeout
来控制连接超时时间。因为DialTimeout
仅在建立连接时起作用,而在etcd
未启动的情况下,连接无法建立。
要设置etcd
客户端的连接超时时间,可以使用clientTimeout
选项。clientTimeout
控制对etcd的请求的超时时间。当etcd
无法响应请求时,客户端将等待指定的时间,然后返回超时错误。
代码示例:
package main
import (
"context"
"fmt"
"time"
"go.etcd.io/etcd/client/v3"
)
func main() {
cfg := clientv3.Config{
Endpoints: []string{"localhost:2379"}, //etcd服务器的地址
DialTimeout: 5 * time.Second, //建立连接的超时时间
}
// 创建etcd客户端
cli, err := clientv3.New(cfg)
if err != nil {
fmt.Printf("创建etcd客户端失败:%v", err)
return
}
defer cli.Close()
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
_, err = cli.Put(ctx, "key", "value")
if err != nil {
fmt.Printf("创建key失败: %v", err)
return
}
fmt.Println("执行成功")
}
未启动etcd的情况下执行代码
创建key失败: context deadline exceeded
在上面的代码中,我们通过将DialTimeout
设置为5秒来设置连接的超时时间。然后,我们使用Put
函数向etcd中插入一个key-value对,并设置了一个短的上下文超时时间为2秒。