Saturday, March 19, 2016

Implement ETCD Watch by using Golang

etcdWatch

一直很喜歡etcd這套key-value store。透過http的方式存取,COREOS也提供強大的Client供使用。
Watch找了很久,終於知道該怎麼寫了,這中間,還依賴了之前安裝了auto-completion (見我之前的Blog),c-x x-o實在太強大了。
不止Watch,還可對不同的操作Watch,以下為代碼。

package main

import (
    "github.com/coreos/etcd/Godeps/_workspace/src/golang.org/x/net/context"
    "github.com/coreos/etcd/client"
    "log"
    "time"
)

func main() {
    cfg := client.Config{
        Endpoints: []string{"http://127.0.0.1:2379"},
        Transport: client.DefaultTransport,
        // set timeout per request to fail fast when the target endpoint is unavailable
        HeaderTimeoutPerRequest: time.Second,
    }
    c, err := client.New(cfg)
    if err != nil {
        log.Fatal(err)
    }
    kapi := client.NewKeysAPI(c)

    watcher := kapi.Watcher("/cred/", &client.WatcherOptions{
        Recursive: true,
    })
    log.Println("redyto run")
    for {
        detail, _ := watcher.Next(context.Background())
        log.Println("redyto run")
        if detail.Action == "expire" {
            log.Println("expire", detail.Node.Key, detail.Node.Value)
        }
        if detail.Action == "set" {
            log.Println("set", detail.Node.Key, detail.Node.Value)
        }
        if detail.Action == "update" {
            log.Println("update")
        }
        if detail.Action == "expired" {
            log.Println("expired")
        }
        if detail.Action == "delete" {
            log.Println("delete")
        }
       }

}

很可惜ETC取消了Lock的功能,相信以後還會開啟的。

No comments:

Post a Comment