golang操作etcd

2 篇文章 0 订阅

一、用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)

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值