使用代码连接etcd

使用clientv3.New创建客户端:

	cli, err := clientv3.New(clientv3.Config{
		Endpoints:   []string{"localhost:2379"},
		DialTimeout: 5 * time.Second,
	})

	if err != nil {
		Logger.Println("connect ETCD error, the error:", err)
		return 
	}
带证书的客户端:
	// load cert
	cert, err := tls.LoadX509KeyPair(etcdCertPath, etcdCertKeyPath)
	if err != nil {
		Logger.Println("load cert error, the error:", err)
		return nil, err
	}
	// load root ca
	caData, err := ioutil.ReadFile(etcdCaPath)
	if err != nil {
		Logger.Println("load root ca error, the error:", err)
		return nil, err
	}
	pool := x509.NewCertPool()
	pool.AppendCertsFromPEM(caData)

	tlsConfig := &tls.Config{
		Certificates: []tls.Certificate{cert},
		RootCAs:      pool,
	}

	var dataType string

	cli, err := clientv3.New(clientv3.Config{
		Endpoints:   endPoints,
		DialTimeout: time.Duration(dialTimeout) * time.Second,
		TLS:         tlsConfig,
	})

	if err != nil {
		Logger.Println("connect ETCD error, the error:", err)
		return nil, err
	}

获取key所对应的value

	resp, err := cli.Get(context.TODO(),key)
	if err != nil {
		Logger.Println("get config from ETCD error, the error:", err)
		return
	}
	dataType = string(ev.Value)
	Logger.Println("data: ",dataType)

获取前缀为xxx的所有value值

	resp, err := cli.Get(context.TODO(),key, clientv3.WithPrefix())
	if err != nil {
		Logger.Println("get config from ETCD error, the error:", err)
		return 
	}

	for _, ev := range resp.Kvs {
		dataType = string(ev.Value)
		Logger.Println("data: ",dataType)
	}

添加key/value

	resp, err := cli.Put(ctx, "key", "value")
	if err != nil {
		……
	}

你可能感兴趣的:(go)