cacheinterface/memcache.go

59 lines
1.0 KiB
Go
Raw Normal View History

2019-10-02 04:10:27 +00:00
package cache
import (
"github.com/bradfitz/gomemcache/memcache"
"time"
)
type MemcacheSettings struct {
Servers []string
}
type MemcacheCache struct {
servers []string
2019-10-02 04:10:27 +00:00
backend *memcache.Client
}
func NewMemcacheCache(s MemcacheSettings) (CacheInterface, error) {
c := memcache.New(s.Servers...)
return &MemcacheCache{
servers: s.Servers,
2019-10-02 04:10:27 +00:00
backend: c,
}, nil
}
func (mc *MemcacheCache) Has(key string) bool {
_, err := mc.backend.Get(key)
return err != nil
}
func (mc *MemcacheCache) Get(key string, dst ...interface{}) ([]byte, error) {
2019-10-02 04:10:27 +00:00
item, err := mc.backend.Get(key)
if err != nil {
return nil, err
}
if len(dst) > 0 && dst[0] != nil {
return decodeDst(item.Value, dst[0])
}
2019-10-02 04:10:27 +00:00
return item.Value, nil
}
func (mc *MemcacheCache) Set(key string, val interface{}, ttl time.Duration) error {
v, err := encodeValue(val)
2019-10-02 04:10:27 +00:00
if err != nil {
return err
2019-10-02 04:10:27 +00:00
}
return mc.backend.Set(&memcache.Item{Key: key, Value: v, Expiration: int32(ttl.Seconds())})
}
func (mc *MemcacheCache) Del(key string) error {
return mc.backend.Delete(key)
}