golang对etcd存取和数值监测的实现
程序员文章站
2022-08-30 12:38:15
测试代码如下
package main
import (
"fmt"
"log"
"time"
"go.etcd.io/etcd/clien...
测试代码如下
package main import ( "fmt" "log" "time" "go.etcd.io/etcd/clientv3" "golang.org/x/net/context" ) var ( dialtimeout = 5 * time.second requesttimeout = 2 * time.second endpoints = []string{"192.168.99.106:2379", "192.168.99.107:2379", "192.168.99.108:2379"} ) func main() { cli, err := clientv3.new(clientv3.config{ endpoints: endpoints, dialtimeout: dialtimeout, }) if err != nil { log.fatal(err) } defer cli.close() key1, value1 := "testkey1", "value" ctx, cancel := context.withtimeout(context.background(), requesttimeout) _, err = cli.put(ctx, key1, value1) cancel() if err != nil { log.println("put failed. ", err) } else { log.printf("put {%s:%s} succeed\n", key1, value1) } ctx, cancel = context.withtimeout(context.background(), requesttimeout) resp, err := cli.get(ctx, key1) cancel() if err != nil { log.println("get failed. ", err) return } for _, kv := range resp.kvs { log.printf("get {%s:%s} \n", kv.key, kv.value) } done := make(chan bool) go func() { wch := cli.watch(context.background(), key1) for item := range wch { for _, ev := range item.events { log.printf("type:%s, key:%s, value:%s\n", ev.type, ev.kv.key, ev.kv.value) } } }() go func() { for cnt := 0; cnt < 11; cnt++ { value := fmt.sprintf("%s%d", "value", cnt) _, err = cli.put(context.background(), key1, value) if err != nil { log.println("put failed. ", err) } else { log.printf("put {%s:%s} succeed\n", key1, value) } } }() <-done log.println("done!") }
测试结果如下
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
上一篇: golang http连接复用方法
下一篇: c# 如何实现一个简单的json解析器