69 lines
1.2 KiB
Go
69 lines
1.2 KiB
Go
package memcache
|
|
|
|
import (
|
|
"github.com/bradfitz/gomemcache/memcache"
|
|
"meow.tf/go/cacheinterface/v2/encoder"
|
|
"time"
|
|
)
|
|
|
|
type Options struct {
|
|
Encoder encoder.Encoder `default:"msgpack"`
|
|
Servers []string `default:"127.0.0.1:11211"`
|
|
}
|
|
|
|
type Cache struct {
|
|
options Options
|
|
servers []string
|
|
client *memcache.Client
|
|
}
|
|
|
|
func New(options Options) (*Cache, error) {
|
|
client := memcache.New(options.Servers...)
|
|
|
|
return &Cache{
|
|
options: options,
|
|
servers: options.Servers,
|
|
client: client,
|
|
}, nil
|
|
}
|
|
|
|
func (mc *Cache) Has(key string) bool {
|
|
_, err := mc.client.Get(key)
|
|
|
|
return err != nil
|
|
}
|
|
|
|
func (mc *Cache) Get(key string, dst any) error {
|
|
item, err := mc.client.Get(key)
|
|
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return encoder.DecodeValue(mc.options.Encoder, item.Value, dst)
|
|
}
|
|
|
|
func (mc *Cache) GetBytes(key string) ([]byte, error) {
|
|
item, err := mc.client.Get(key)
|
|
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return item.Value, nil
|
|
}
|
|
|
|
func (mc *Cache) Set(key string, val any, ttl time.Duration) error {
|
|
v, err := encoder.EncodeValue(mc.options.Encoder, val)
|
|
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return mc.client.Set(&memcache.Item{Key: key, Value: v, Expiration: int32(ttl.Seconds())})
|
|
}
|
|
|
|
func (mc *Cache) Del(key string) error {
|
|
return mc.client.Delete(key)
|
|
}
|