etcd客户端(二)

Centos7 系统:

#yum install etcd

Centos8 系统:

暂不支持yum安装etcd,可以git clone 安装

C/S 框架

启动配置文件:

/etc/etcd/etcd.conf

启动命令:

etcd -data-dir ~/vpp.etcd -advertise-client-urls http://0.0.0.0:2379 -listen-client-urls http://0.0.0.0:2379

数据存储在 vpp.etcd

启动服务后,搞个客户端程序就可以正常使用了

Etcd 客户端程序

package etcdclient

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

var (
	//Deal with the timeout
	dialTimeout = 5 * time.Second
	//RequestTimeout The request timeout
	RequestTimeout = 10 * time.Second
)

var etcdCliV3 *clientv3.Client

//New ETCD client
func GetEtcdClientV3() (cli *clientv3.Client, err error) {
	if etcdCliV3 != nil {
		cli = etcdCliV3
		err = nil
	} else {
		cli = nil
		err = fmt.Errorf("etcdCliV3 not initialized")
	}
	return
}

//Create a new ETCD client connection
func NewEtcdClientV3(endpoint []string) (cli *clientv3.Client, err error) {

	fmt.Printf("the etcd link -%s\n", endpoint)
	cli, err = clientv3.New(clientv3.Config{
		Endpoints:   endpoint,
		DialTimeout: dialTimeout,
	})

	if err != nil {
		// handle error!
		log.Error("agent connect etcd failed: %v", err)
		os.Exit(1)
	}
	etcdCliV3 = cli
	log.Info("connect etcd successfully")
	return
}

//close etcd client
func CloseEtcdClientV3() {
	etcdCliV3.Close()
	log.Info("close etcd client connection")
}

//Sets the keys and values for the ETCD
func EtcdClientV3Put(key string, val string) (err1 error) {
	//...
	return
}

//Delete the value of the key
func EtcdClientV3Del(key string) (err1 error) {
	//...
}

//Gets the value of the key
func EtcdClientV3Get(key string) (result string, err1 error) {
	//...
}

//EtcdClientV3GetPrefix Get the data from the ETCD database
func EtcdClientV3GetPrefix(key string, onGet func([]byte, []byte)) (err1 error) {
	//...
}

//EtcdClientV3DeleteAll Empty the ETCD database
func EtcdClientV3DeleteAll() (err error) {
	if etcdCliV3 == nil {
		return fmt.Errorf("cli not initialize")
	}
	ctx, cancel := context.WithTimeout(context.Background(), RequestTimeout)
	_, err = etcdCliV3.Delete(ctx, "", clientv3.WithPrefix())
	cancel()
	if err != nil {
		switch err {
		case context.Canceled:
			log.Info("ctx is canceled by another routine: %v", err)
		case context.DeadlineExceeded:
			log.Info("ctx is attached with a deadline is exceeded: %v", err)
		default:
			log.Info("bad cluster endpoints, which are not etcd servers: %v", err)
		}
		return err
	}

	return nil
}

func main(){
	//...
	
	etcdclient.NewEtcdClientV3("[127.0.0.1:2379]")
	
	//...请开始你的业务表演
	
	<-c
	etcdclient.CloseEtcdClientV3()
	
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值