欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

etcd入门

程序员文章站 2022-07-13 23:15:02
...

etcd入门

​ etcd是分布式协调框架,基本和zookeeper功能和场景相似。它使用高可用的k-v键值对做数据库,采用raft一致性算法。采用Go语言实现。

​ etcd使用gRPC对外提供API。总共分为三类

  • Kv:key-value的创建、更新、读取和删除
  • watch:提供监控数据更新的机制
  • Lease :用来支持客户端的keep-alive的消息 可以设置lease和key进行绑定,当lease释放后,key就会被删除,相当于zk中的临时性节点

etcd本地安装

Mac : etcd-v3.4.13-darwin-amd64.zip

linux: etcd-v3.4.13-linux-amd64.tar.gz

Windows: etcd-v3.4.13-windows-amd64.zip

下载后解压即可

etcd启动

cd "解压目录"
etcd # 启动etcd standalone
etcdctl # etcd控制的工具
etcdctl put foo value1
etcdctl get foo

Go连接etcd并使用v3Client操作etcd

package main

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

func main() {
	cli, err := clientv3.New(clientv3.Config{
		Endpoints:   []string{"localhost:2379"},
		DialTimeout: 5 * time.Second,
	})
	if err != nil {
		fmt.Println("failed to create client")
	}
	defer cli.Close()
	ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
	resp, err := cli.Put(ctx, "cpf", "zzc1")
	cancel()
	if err != nil {
		fmt.Println("failed to put")
	}
	// use the response
	fmt.Println("resp", resp)
}
module declares its path as: go.etcd.io/bbolt
	        but was required as: github.com/coreos/bbolt

使用etcd v3Client可能遇到几个问题:

  1. module declares its path as: go.etcd.io/bbolt but was required as: github.com/coreos/bbolt(包依赖冲突)
   replace github.com/coreos/bbolt v1.3.5 => go.etcd.io/bbolt v1.3.5
   
   replace go.etcd.io/bbolt v1.3.5 => github.com/coreos/bbolt v1.3.5
  1. etcd undefined: resolver.BuildOption (版本依赖冲突)

    go mod edit -require=google.golang.org/[email protected]
    go get -u -x google.golang.org/[email protected]
    go build