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