memcache a go
This commit is contained in:
49
cache.go
Normal file
49
cache.go
Normal file
@@ -0,0 +1,49 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"os"
|
||||
"time"
|
||||
|
||||
cache "github.com/patrickmn/go-cache"
|
||||
)
|
||||
|
||||
type Cache struct {
|
||||
db *cache.Cache
|
||||
path string
|
||||
}
|
||||
|
||||
func NewCache(path ...string) (*Cache, error) {
|
||||
var err error = nil
|
||||
c := &Cache{db: cache.New(0, time.Minute*15), path: ""}
|
||||
if len(path) != 0 {
|
||||
c.path = path[0]
|
||||
if _, err := os.Stat(c.path); err == nil {
|
||||
err = c.db.LoadFile(c.path)
|
||||
}
|
||||
}
|
||||
return c, err
|
||||
}
|
||||
|
||||
func (c *Cache) Get(key string) ([]byte, error) {
|
||||
v, ok := c.db.Get(key)
|
||||
if !ok {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
b, ok := v.([]byte)
|
||||
if !ok {
|
||||
return nil, ErrNotImpl
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
|
||||
func (c *Cache) Set(key string, value []byte) error {
|
||||
c.db.Set(key, value, 0)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Cache) Close() error {
|
||||
if c.path != "" {
|
||||
return c.db.SaveFile(c.path)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user