首页 > 其他分享 >go etcd clientV3 带tls demo

go etcd clientV3 带tls demo

时间:2022-09-01 17:56:04浏览次数:69  
标签:clientV3 tls cli err clientv3 fmt etcd go

go 操作etcdV3

终端操作etcd链接:https://www.cnblogs.com/zisefeizhu/p/15427799.html

安装etcd clientV3
$ get go.etcd.io/etcd/clientv3            
# github.com/coreos/etcd/clientv3/balancer/resolver/endpoint
../../../go/pkg/mod/github.com/coreos/[email protected]+incompatible/clientv3/balancer/resolver/endpoint/endpoint.go:114:78: undefined: resolver.BuildOption
../../../go/pkg/mod/github.com/coreos/[email protected]+incompatible/clientv3/balancer/resolver/endpoint/endpoint.go:182:31: undefined: resolver.ResolveNowOption
# github.com/coreos/etcd/clientv3/balancer/picker
../../../go/pkg/mod/github.com/coreos/[email protected]+incompatible/clientv3/balancer/picker/err.go:37:44: undefined: balancer.PickOptions
../../../go/pkg/mod/github.com/coreos/[email protected]+incompatible/clientv3/balancer/picker/roundrobin_balanced.go:55:54: undefined: balancer.PickOptions

# 修复
$  go get -u -x google.golang.org/[email protected]
etcd clientV3 配置TLS 证书

clientv3.Config struct 的 TLS 字段 :TLS 持有客户端安全凭证(如果有)

构建tls
// 证书
tlsInfo := transport.TLSInfo{
    TrustedCAFile: etcdCa,
    CertFile:      etcdCert,
    KeyFile:       etcdCertKey,
}
_tlsConfig, err := tlsInfo.ClientConfig()
if err != nil {
    fmt.Printf("tlsconfig failed, err:%v\n", err)
}

证书对应终端操作etcd链接

TrustedCAFile: --cacert

CertFile: --cert

KeyFile: --key

go etcd client 简单操作
cfg := clientv3.Config{
    Endpoints:   endpoints,
    DialTimeout: dialTimeout,
    TLS:         _tlsConfig,
}

cli, err := clientv3.New(cfg)
if err != nil {
    fmt.Printf("connect to etcd failed, err:%v\n", err)
    return
}
defer cli.Close()

ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
putResponse, err := cli.Put(ctx, "zise", "feizhu")
cancel()
if err != nil {
    fmt.Printf("put to etcd failed, err:%v\n", err)
    return
}
fmt.Println(putResponse)
ctx, cancel = context.WithTimeout(context.Background(), time.Second)
getResponse, err := cli.Get(ctx, "zise")
cancel()
if err != nil {
    fmt.Printf("get to etcd failed, err:%v\n", err)
    return
}
fmt.Println(getResponse)
deleteResponse, err := cli.Delete(cli.Ctx(), "zise")
if err != nil {
    fmt.Printf("delete to etcd failed, err:%v\n", err)
    return
}
fmt.Println(deleteResponse)
go etcd clientV3 demo

目录结构

源码

package main

import (
	"context"
	"fmt"
	"go.etcd.io/etcd/clientv3"
	"go.etcd.io/etcd/pkg/transport"
	"os"
	"time"
)

func init() {
	var err error
	dir, err = os.Getwd()
	if err != nil {
		fmt.Printf("getwd dir err:%v\n", err)
		return
	}
	etcdCert = dir + "/tls/etcd/server.crt"
	etcdCertKey = dir + "/tls/etcd/server.key"
	etcdCa = dir + "/tls/etcd/ca.crt"
}

var (
	dir            string
	dialTimeout    = 5 * time.Second
	// requestTimeout = 4 * time.Second
	endpoints      = []string{"https://1.1.1.45:2379", "https://1.1.1.46:2379", "https://1.1.1.47:2379"}
	etcdCert       string
	etcdCertKey    string
	etcdCa         string
)

func main() {
	// 证书
	tlsInfo := transport.TLSInfo{
		TrustedCAFile: etcdCa,
		CertFile:      etcdCert,
		KeyFile:       etcdCertKey,
	}
	_tlsConfig, err := tlsInfo.ClientConfig()
	if err != nil {
		fmt.Printf("tlsconfig failed, err:%v\n", err)
	}

	cfg := clientv3.Config{
		Endpoints:   endpoints,
		DialTimeout: dialTimeout,
		TLS:         _tlsConfig,
	}

	cli, err := clientv3.New(cfg)
	if err != nil {
		fmt.Printf("connect to etcd failed, err:%v\n", err)
		return
	}
	defer cli.Close()

	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
	putResponse, err := cli.Put(ctx, "zise", "feizhu")
	cancel()
	if err != nil {
		fmt.Printf("put to etcd failed, err:%v\n", err)
		return
	}
	fmt.Println(putResponse)
	ctx, cancel = context.WithTimeout(context.Background(), time.Second)
	getResponse, err := cli.Get(ctx, "zise")
	cancel()
	if err != nil {
		fmt.Printf("get to etcd failed, err:%v\n", err)
		return
	}
	fmt.Println(getResponse)
	deleteResponse, err := cli.Delete(cli.Ctx(), "zise")
	if err != nil {
		fmt.Printf("delete to etcd failed, err:%v\n", err)
		return
	}
	fmt.Println(deleteResponse)
}

测试

$ go run main.go 
{cluster_id:16977795579664915518 member_id:15527552572173850242 revision:382574450 raft_term:8330  <nil> {} [] 0}
{cluster_id:16977795579664915518 member_id:5537999761451951234 revision:382574450 raft_term:8330  [key:"zise" create_revision:382574450 mod_revision:382574450 version:1 value:"feizhu" ] false 1 {} [] 0}
{cluster_id:16977795579664915518 member_id:8044152919570031487 revision:382574451 raft_term:8330  1 [] {} [] 0}

标签:clientV3,tls,cli,err,clientv3,fmt,etcd,go
From: https://www.cnblogs.com/zisefeizhu/p/16647380.html

相关文章

  • Go ORM框架ent快速上手
    https://entgo.io/docs/getting-startedhttps://github.com/ent/entent是一款facebook开源的go语言ORM框架,类似于gorm等用于实现数据库对象映射和操作的框架。ent的不同......
  • [Google] LeetCode 150 Evaluate Reverse Polish Notation
    EvaluatethevalueofanarithmeticexpressioninReversePolishNotation.Validoperatorsare+,-,*,and/.Eachoperandmaybeanintegeroranotherexpres......
  • go两个结构体赋值相同类型和名称的字段(测试)
    packagemainimport( "fmt" "reflect" "time")typeTAstruct{ Id*int32`json:"id"` TTTT`json:"tt"` ArrArray[int32]`json:"ar......
  • Go 语言入门 1-管道的特性及实现原理
    入坑go也快一年了,从今天开始会定期分享一下Go语言学习过程中的一些基础知识。 go语言中的管道,主要是用于协程之间的通信,比UNIX的管道更加轻量和易用。 我们......
  • 修改mongodb的缓存大小
    在admin下首先查询当前cache大小db.serverStatus().wiredTiger.cache['maximumbytesconfigured']/1024/1024/1024 方法一:修改配置文件mongod.conf添加内容如下s......
  • 给正在运行的mongodb启动添加配置文件
    因为一开始启动容器的时候就没有指定配置文件,无论怎么修改容器中的/etc/mongd.conf.org文件都无法生效所以直接修改启动脚本添加$@的参数实现1、复制容器中的文件/usr/lo......
  • go map键类型小记
    一、Go语言map的键类型不可以是函数类型、字典类型和切片类型。因为map键值需要可以做hash操作,而func,map,slice不支持这些操作。 报错:  并且,一般Struct可以支持ha......
  • sprinngboot+Mongodb
    参考:https://blog.csdn.net/m0_46742141/article/details/121845098 maven依赖<dependency><groupId>org.springframework.boot</groupId>......
  • Django国际化
    安装python环境并配置系统变量安装django:pipinstallDjangoCMD中输入django-admin 看看是否有命令提示输出,如果没有,将”xxxxx\Roaming\Python\Python39\Scripts”加......
  • MongoDB 实现中文全文搜索
    Prerequisite倒排索引是所有支持全文搜索的数据库的基础。比如iamironman和iwillbesoonback,欲查找be,先查第一句,再查第二局,这是正排;将每个单词提取出来形成一个......