码迷,mamicode.com
首页 > 其他好文 > 详细

Go etcd初探

时间:2018-04-28 21:09:06      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:ring   ref   context   func   EOS   core   color   .config   集群   

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初探

标签:ring   ref   context   func   EOS   core   color   .config   集群   

原文地址:https://www.cnblogs.com/mrblue/p/8969348.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!