Go etcd初探

Posted MrBlue

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Go etcd初探相关的知识,希望对你有一定的参考价值。

1.etcd集群的配置

SET IP1_2380=http://127.0.0.1:2380
SET IP1_2379=http://127.0.0.1:2379

SET IP2_2380=http://127.0.0.1:3380
SET IP2_2379=http://127.0.0.1:3379

SET IP3_2380=http://127.0.0.1:4380
SET IP3_2379=http://127.0.0.1:4379

SET SELF_2380=%IP1_2380%
SET SELF_2379=%IP1_2379%

etcd -name niub1 -debug -initial-advertise-peer-urls %SELF_2380% -listen-peer-urls %SELF_2380% -listen-client-urls %SELF_2379% -advertise-client-urls %SELF_2379% -initial-cluster niub1=%IP1_2380%,niub2=%IP2_2380%,niub3=%IP3_2380%

  

创建3个这个脚本,分别改

SET SELF_2380=%IP1_2380%
SET SELF_2379=%IP1_2379%






2、Go测试程序代码
package main

import (
    "context"
    "flag"
    "log"
    "strings"
    "time"

    "github.com/coreos/etcd/mvcc/mvccpb"

    "github.com/coreos/etcd/clientv3"
)

var (
    addr = flag.String("addr", "127.0.0.1:2380", "etcd addr")
)

func main() {
    flag.Parse()

    addrs := strings.Split(*addr, ",")

    cli, err := clientv3.New(clientv3.Config{
        Endpoints: addrs,
    })

    if nil != err {
        panic(err)
    }

    defer cli.Close()

    if _, err := cli.Put(context.TODO(), "haha", "{1,1,3}"); nil != err {
        log.Fatal(err)
    }

    {
        resp, err := cli.Get(context.TODO(), "haha")
        if nil != err {
            log.Fatal(err)
        }
        log.Println("resp=", resp)
    }

    go func() {

        timer := time.NewTimer(time.Second * 20)
        ticker := time.NewTicker(time.Second * 2)

        for {
            select {
            case <-ticker.C:
                resp, _ := cli.Grant(context.TODO(), 1)
                ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
                cli.Put(ctx, "node1", `{"addr":"192.168.1.1:9999"}`, clientv3.WithLease(resp.ID))
            case <-timer.C:
                return
            }
        }
    }()

    { //watch
        rch := cli.Watch(context.Background(), "", clientv3.WithPrefix())
        for wresp := range rch {
            for _, ev := range wresp.Events {
                log.Println(ev)
                if ev.IsCreate() {
                    log.Println("IsCreate")
                } else if ev.IsModify() {
                    log.Println("IsModify")
                } else if ev.Type == mvccpb.DELETE {
                    log.Println("DELETE")
                } else if ev.Type == mvccpb.PUT {
                    log.Println("PUT")
                }

            }
        }
    }

}

3、启动测试

启动时传入参数 

-addr=127.0.0.1:2380,127.0.0.1:3380,127.0.0.1:4380
 




以上是关于Go etcd初探的主要内容,如果未能解决你的问题,请参考以下文章

etcd v3 服务注册与发现 Go代码

go任务调度5(go操作etcd)

etcd Raft 源码剖析

etcd Raft 源码剖析

etcd Raft 源码剖析

etcd Raft 源码剖析