Skip to content

Expose a standard KV operation API, adapt to embeded etcd and etcd client

License

Notifications You must be signed in to change notification settings

go-chassis/etcdadpt

Repository files navigation

etcd-adapter

Expose a standard KV operation API, adapt to embeded etcd and etcd client

How to use?

Step 1. Import the module and it's all plugins.

import (
	github.com/go-chassis/etcdadpt
	_ "github.com/go-chassis/etcdadpt/embedded"
	_ "github.com/go-chassis/etcdadpt/remote"
)

Step 2. Select one mode and do initialization.

With embedded etcd mode:

etcdadpt.Init(etcdadpt.Config{
	Kind:             "embedded_etcd",
	ClusterName:      "c-0",
	ClusterAddresses: "c-0=http://127.0.0.1:2379",
})

This mode will start an embedded etcd server.

With remote etcd mode:

startup etcd server.

docker run -d  -p 2379:2379 --name etcd quay.io/coreos/etcd:v3.2.13 etcd \
  --listen-client-urls http://0.0.0.0:2379 --advertise-client-urls http://0.0.0.0:2379

write the following code.

etcdadpt.Init(etcdadpt.Config{
	Kind:             "etcd",
	ClusterAddresses: "127.0.0.1:2379",
})

Step 3. call the API and enjoy it!

// put a key
_ := etcdadpt.Put(context.Background(), "/key", "abc")
// get a key
kv, _ := etcdadpt.Get(context.Background(), "/key")
log.Println(fmt.Sprintf("%v", kv))

and you will see log print below:

key:"/key" create_revision:4 mod_revision:4 version:1 value:"abc"

Distributed Etcd lock

example

lock, _ := etcdadpt.Lock("/test", -1)
defer lock.Unlock()
//do something
g += 1
fmt.Println(g)
// lock a key for a period of time, and then renew
dLock, err := etcdadpt.Lock("renewKey", 5)
time.Sleep(3 * time.Second)
err = dLock.Refresh()

Examples

Also see the full demo HERE!

About

Expose a standard KV operation API, adapt to embeded etcd and etcd client

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors 4

  •  
  •  
  •  
  •  

Languages