-
Notifications
You must be signed in to change notification settings - Fork 10.2k
Closed
Labels
Description
my code:
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"os"
"os/signal"
"syscall"
"time"
"go.etcd.io/etcd/v3/clientv3"
)
var endPoints = []string{
"192.168.0.11:2379",
// "192.168.0.12:2379",
// "192.168.0.13:2379",
}
var wait = 3 * time.Second
func main() {
log.Println("test etcd")
cli, err := clientv3.New(clientv3.Config{
Endpoints: endPoints,
DialTimeout: 5 * time.Second,
})
if err != nil {
// handle error
log.Fatalln("etcd connection error: ", err)
}
defer cli.Close()
// 设置超时
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
_, err = cli.Put(ctx, "name", "Jaye")
defer cancel()
if err != nil {
log.Println("cli.Put", err.Error())
}
// 取值
ctx, cancel = context.WithTimeout(context.Background(), 5*time.Second)
res, err := cli.Get(ctx, "/test/ok")
if err != nil {
log.Println("cli.Get", err.Error())
}
for k, v := range res.Kvs {
fmt.Println("查询结果", k, string(v.Key), string(v.Value))
}
// watch
// for {
// rch := cli.Watch(context.Background(), "home")
// for resp := range rch {
// for k, v := range resp.Events {
// fmt.Println(k, v.Type, string(v.Kv.Key), string(v.Kv.Value))
// }
// }
// }
watchConfig(cli, "config_key", &appConfig)
//平滑重启
ch := make(chan os.Signal, 1)
// We'll accept graceful shutdowns when quit via SIGINT (Ctrl+C)
// recivie signal to exit main goroutine
// window signal
signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM, os.Interrupt, syscall.SIGHUP)
// linux signal if you use linux on production,please use this code.
// signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM, syscall.SIGUSR2, os.Interrupt, syscall.SIGHUP)
// Block until we receive our signal.
sig := <-ch
log.Println("exit signal: ", sig.String())
// Create a deadline to wait for.
ctx, cancel = context.WithTimeout(context.Background(), wait)
defer cancel()
<-ctx.Done()
log.Println("shutting down")
}
// AppConfig 应用config
type AppConfig struct {
AppID string `json:"app_id"`
AppName string `json:"app_name`
}
var appConfig AppConfig
// watchConfig 监听配置变化
func watchConfig(clt *clientv3.Client, key string, ss interface{}) {
watchCh := clt.Watch(context.TODO(), key)
go func() {
for res := range watchCh {
value := res.Events[0].Kv.Value
if err := json.Unmarshal(value, ss); err != nil {
fmt.Println("now", time.Now(), "watchConfig err", err)
continue
}
fmt.Println("now", time.Now(), "watchConfig", ss)
}
}()
}
$ go mod tidy
go.etcd.io/etcd/clientv3 tested by
go.etcd.io/etcd/clientv3.test imports
github.com/coreos/etcd/auth imports
github.com/coreos/etcd/mvcc/backend imports
github.com/coreos/bbolt: github.com/coreos/bbolt@v1.3.4: parsing go.mod:
module declares its path as: go.etcd.io/bbolt
but was required as: github.com/coreos/bbolt
spiilmusic, PatrLind, Zmingfeng, pinylin, kirinshow and 5 more