Go etcd初探

时间:2023-03-08 16:32:05

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 * )
ticker := time.NewTicker(time.Second * ) for {
select {
case <-ticker.C:
resp, _ := cli.Grant(context.TODO(), )
ctx, _ := context.WithTimeout(context.Background(), *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