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 {
|
2019-10-03 00:36:45 +00:00
|
|
|
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{
|
2019-10-03 00:36:45 +00:00
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2019-10-03 00:17:34 +00:00
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2019-10-03 00:17:34 +00:00
|
|
|
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 {
|
2019-10-03 00:17:34 +00:00
|
|
|
v, err := encodeValue(val)
|
2019-10-02 04:10:27 +00:00
|
|
|
|
2019-10-03 00:17:34 +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)
|
|
|
|
}
|