micro/store/memcached/memcached.go

71 lines
1.1 KiB
Go
Raw Normal View History

package memcached
2015-01-13 23:31:27 +00:00
import (
"errors"
mc "github.com/bradfitz/gomemcache/memcache"
"github.com/myodc/go-micro/store"
2015-01-13 23:31:27 +00:00
)
type mstore struct {
2015-01-13 23:31:27 +00:00
Client *mc.Client
}
type item struct {
key string
value []byte
}
func (i *item) Key() string {
return i.key
}
func (i *item) Value() []byte {
return i.value
}
func (m *mstore) Get(key string) (store.Item, error) {
2015-01-13 23:31:27 +00:00
kv, err := m.Client.Get(key)
if err != nil && err == mc.ErrCacheMiss {
return nil, errors.New("key not found")
} else if err != nil {
return nil, err
}
if kv == nil {
return nil, errors.New("key not found")
}
return &item{
2015-01-13 23:31:27 +00:00
key: kv.Key,
value: kv.Value,
}, nil
}
func (m *mstore) Del(key string) error {
2015-01-13 23:31:27 +00:00
return m.Client.Delete(key)
}
func (m *mstore) Put(item store.Item) error {
2015-01-13 23:31:27 +00:00
return m.Client.Set(&mc.Item{
Key: item.Key(),
Value: item.Value(),
})
}
func (m *mstore) NewItem(key string, value []byte) store.Item {
return &item{
2015-01-13 23:31:27 +00:00
key: key,
value: value,
}
}
func NewStore(addrs []string, opts ...store.Option) store.Store {
if len(addrs) == 0 {
addrs = []string{"127.0.0.1:11211"}
2015-01-13 23:31:27 +00:00
}
return &mstore{
Client: mc.New(addrs...),
2015-01-13 23:31:27 +00:00
}
}