Etcd 是一个高可用的键值对存储系统,可以用它实现服务配置;服务发现 Etcd 使用 raft 一致性协议保证数据、服务的高可用 Etcd 提供了 rest 方法进行 api 的操作

Etcd 参数说明

Etcd restful 接口

启动一个单机的 etcd 直接执行 etcd

练习使用restful 接口调用

Postman请求封装

Golang 调用 Etcd Api

package main

import (
	"fmt"
	"os"
	"os/signal"
	"syscall"
	"time"

	"github.com/coreos/etcd/clientv3"
	"golang.org/x/net/context"
	"google.golang.org/grpc/grpclog"
)

func main() {

	clientv3.SetLogger(grpclog.NewLoggerV2(os.Stderr, os.Stderr, os.Stderr))

	cli, err := clientv3.New(clientv3.Config{
		Endpoints:   []string{"localhost:2379", "localhost:2389", "localhost:2399", "localhost:2409"},
		DialTimeout: 5 * time.Second,
		Username:    "root",
		Password:    "123456",
	})
	if err != nil {
		panic(err.Error())
	}
	defer cli.Close()

	//fmt.Printf("%#v\n", cli)
	cli.Put(context.TODO(), "/foo1", "go-key1-val")
	resp, err := cli.Get(context.TODO(), "/foo1")
	//fmt.Println(resp, err)
	for k, v := range resp.Kvs {
		fmt.Printf("--- %#v, %v %v\n", k, string(v.Key), string(v.Value))
	}

	go func() {
		fmt.Println("in change watcher data")

		timer := time.NewTicker(time.Second * 2)
		defer timer.Stop()

		for {
			select {
			case <-timer.C:
				fmt.Println("get timer")
				cli.Put(context.TODO(), "/foo1", fmt.Sprintf("go-timer-%d", time.Now().Unix()))
			}
		}

	}()

	go func() {
		fmt.Println("in watcher.......")
		wch := cli.Watch(context.TODO(), "/foo1")
		for {
			dwch := <-wch
			fmt.Printf("get new watch data =>%#v\n", dwch)
		}
	}()

	sn := make(chan os.Signal)
	signal.Notify(sn, syscall.SIGKILL)
	<-sn
}

集群配置

单机配置

服务一配置信息

etcd --name infra0 --initial-advertise-peer-urls http://127.0.0.1:2380 \
  --listen-peer-urls http://127.0.0.1:2380 \
  --listen-client-urls http://127.0.0.1:2379 \
  --advertise-client-urls http://127.0.0.1:2379 \
  --initial-cluster-token etcd-cluster-1 \
  --initial-cluster infra0=http://127.0.0.1:2380,infra1=http://127.0.0.1:2390,infra2=http://127.0.0.1:2400 \
  --initial-cluster-state new

服务二配置信息

etcd --name infra1 --initial-advertise-peer-urls http://127.0.0.1:2390 \
  --listen-peer-urls http://127.0.0.1:2390 \
  --listen-client-urls http://127.0.0.1:2389 \
  --advertise-client-urls http://127.0.0.1:2389 \
  --initial-cluster-token etcd-cluster-1 \
  --initial-cluster infra0=http://127.0.0.1:2380,infra1=http://127.0.0.1:2390,infra2=http://127.0.0.1:2400 \
  --initial-cluster-state new

服务三配置信息

etcd --name infra2 --initial-advertise-peer-urls http://127.0.0.1:2400 \
  --listen-peer-urls http://127.0.0.1:2400 \
  --listen-client-urls http://127.0.0.1:2399 \
  --advertise-client-urls http://127.0.0.1:2399 \
  --initial-cluster-token etcd-cluster-1 \
  --initial-cluster infra0=http://127.0.0.1:2380,infra1=http://127.0.0.1:2390,infra2=http://127.0.0.1:2400 \
  --initial-cluster-state new

送上一个简单的启动脚本