2015-05-23 22:04:16 +03:00
|
|
|
package etcd
|
2015-02-07 23:12:57 +03:00
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
|
|
|
|
"github.com/coreos/go-etcd/etcd"
|
2015-05-23 22:04:16 +03:00
|
|
|
"github.com/myodc/go-micro/store"
|
2015-02-07 23:12:57 +03:00
|
|
|
)
|
|
|
|
|
2015-05-23 22:04:16 +03:00
|
|
|
type estore struct {
|
2015-02-07 23:12:57 +03:00
|
|
|
Client *etcd.Client
|
|
|
|
}
|
|
|
|
|
2015-05-23 22:04:16 +03:00
|
|
|
type item struct {
|
|
|
|
key string
|
|
|
|
value []byte
|
|
|
|
}
|
|
|
|
|
|
|
|
func (i *item) Key() string {
|
|
|
|
return i.key
|
|
|
|
}
|
|
|
|
|
|
|
|
func (i *item) Value() []byte {
|
|
|
|
return i.value
|
|
|
|
}
|
|
|
|
|
|
|
|
func (e *estore) Get(key string) (store.Item, error) {
|
2015-02-07 23:12:57 +03:00
|
|
|
kv, err := e.Client.Get(key, false, false)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
if kv == nil {
|
|
|
|
return nil, errors.New("key not found")
|
|
|
|
}
|
|
|
|
|
2015-05-23 22:04:16 +03:00
|
|
|
return &item{
|
2015-02-07 23:12:57 +03:00
|
|
|
key: kv.Node.Key,
|
|
|
|
value: []byte(kv.Node.Value),
|
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
2015-05-23 22:04:16 +03:00
|
|
|
func (e *estore) Del(key string) error {
|
2015-02-07 23:12:57 +03:00
|
|
|
_, err := e.Client.Delete(key, false)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2015-05-23 22:04:16 +03:00
|
|
|
func (e *estore) Put(item store.Item) error {
|
2015-02-07 23:12:57 +03:00
|
|
|
_, err := e.Client.Set(item.Key(), string(item.Value()), 0)
|
|
|
|
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2015-05-23 22:04:16 +03:00
|
|
|
func (e *estore) NewItem(key string, value []byte) store.Item {
|
|
|
|
return &item{
|
2015-02-07 23:12:57 +03:00
|
|
|
key: key,
|
|
|
|
value: value,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-05-23 22:04:16 +03:00
|
|
|
func NewStore(addrs []string, opts ...store.Option) store.Store {
|
2015-05-16 02:34:02 +03:00
|
|
|
if len(addrs) == 0 {
|
|
|
|
addrs = []string{"127.0.0.1:2379"}
|
|
|
|
}
|
|
|
|
|
|
|
|
client := etcd.NewClient(addrs)
|
2015-02-07 23:12:57 +03:00
|
|
|
|
2015-05-23 22:04:16 +03:00
|
|
|
return &estore{
|
2015-02-07 23:12:57 +03:00
|
|
|
Client: client,
|
|
|
|
}
|
|
|
|
}
|