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

golang操作etcd

程序员文章站 2022-07-13 22:10:54
...

一、用docker-compose部署etcd
docker-compose.yaml文件内容

version: '2'
networks:
 byfn:

 services:
etcd1:
 image: quay.io/coreos/etcd
	container_name: etcd1
	command: etcd -name etcd1 -advertise-client-urls http://0.0.0.0:2379 -listen-client-urls http://0.0.0.0:2379 -listen-peer-urls http://0.0.0.0:2380 -initial-cluster-token etcd-cluster -initial-cluster "etcd1=http://etcd1:2380,etcd2=http://etcd2:2380,etcd3=http://etcd3:2380" -initial-cluster-state new
ports:
  - 2379
  - 2380
networks:
  - byfn

etcd2:
image: quay.io/coreos/etcd
container_name: etcd2
command: etcd -name etcd2 -advertise-client-urls http://0.0.0.0:2379 -listen-client-urls http://0.0.0.0:2379 -listen-peer-urls http://0.0.0.0:2380 -initial-cluster-token etcd-cluster -initial-cluster "etcd1=http://etcd1:2380,etcd2=http://etcd2:2380,etcd3=http://etcd3:2380" -initial-cluster-state new
ports:
  - 2379
  - 2380
networks:
  - byfn

etcd3:
image: quay.io/coreos/etcd
container_name: etcd3
command: etcd -name etcd3 -advertise-client-urls http://0.0.0.0:2379 -listen-client-urls http://0.0.0.0:2379 -listen-peer-urls http://0.0.0.0:2380 -initial-cluster-token etcd-cluster -initial-cluster "etcd1=http://etcd1:2380,etcd2=http://etcd2:2380,etcd3=http://etcd3:2380" -initial-cluster-state new
ports:
  - 2379
  - 2380
networks:
  - byfn

2、golang操作etcd

package main

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

func main() {
	//链接etcd
	cfg := client.Config{
		Endpoints: []string{"http://127.0.0.1:32799/", "http://127.0.0.1:32801/", "http://127.0.0.1:32803/"},
		Transport: client.DefaultTransport,
		//set timeout per request to fail fast when the target endpoint is unavailable
		HeaderTimeoutPerRequest: time.Second,
	}
	c, _ := client.New(cfg)
	keysApi := client.NewKeysAPI(c)

	//读取etcd
	res, err := keysApi.Get(context.Background(), "job", nil)
	fmt.Println("res====>", res)
	fmt.Println("err====>", err)
	//添加etcd
	res1, err := keysApi.Set(context.Background(), "work", "This is my work", nil)
	fmt.Println("res1===>", res1)
	fmt.Println("err===>", err)
	//读取etcd
	values, err := keysApi.Get(context.Background(), "work", nil)
	fmt.Println("values====>", values)
	fmt.Println("err====>", err)
	//更新etcd
	up, err := keysApi.Update(context.Background(), "job", "my job")
	fmt.Println("up====>", up)
	fmt.Println("err====>", err)
	//删除
	del, err := keysApi.Delete(context.Background(), "work", nil)
	fmt.Println("del====>", del)
	fmt.Println("err====>", err)

}