1
0
mirror of https://github.com/astaxie/beego.git synced 2024-11-25 18:50:55 +00:00
This commit is contained in:
astaxie 2016-08-30 21:24:56 +08:00
parent 1e1e900278
commit 7df74c0a30

View File

@ -33,12 +33,10 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"strings" "strings"
"github.com/bradfitz/gomemcache/memcache"
"time" "time"
"github.com/astaxie/beego/cache" "github.com/astaxie/beego/cache"
"github.com/bradfitz/gomemcache/memcache"
) )
// Cache Memcache adapter. // Cache Memcache adapter.
@ -60,7 +58,7 @@ func (rc *Cache) Get(key string) interface{} {
} }
} }
if item, err := rc.conn.Get(key); err == nil { if item, err := rc.conn.Get(key); err == nil {
return string(item.Value) return item.Value
} }
return nil return nil
} }
@ -80,7 +78,7 @@ func (rc *Cache) GetMulti(keys []string) []interface{} {
mv, err := rc.conn.GetMulti(keys) mv, err := rc.conn.GetMulti(keys)
if err == nil { if err == nil {
for _, v := range mv { for _, v := range mv {
rv = append(rv, string(v.Value)) rv = append(rv, v.Value)
} }
return rv return rv
} }
@ -90,18 +88,21 @@ func (rc *Cache) GetMulti(keys []string) []interface{} {
return rv return rv
} }
// Put put value to memcache. only support string. // Put put value to memcache.
func (rc *Cache) Put(key string, val interface{}, timeout time.Duration) error { func (rc *Cache) Put(key string, val interface{}, timeout time.Duration) error {
if rc.conn == nil { if rc.conn == nil {
if err := rc.connectInit(); err != nil { if err := rc.connectInit(); err != nil {
return err return err
} }
} }
v, ok := val.(string) item := memcache.Item{Key: key, Expiration: int32(timeout / time.Second)}
if !ok { if v, ok := val.([]byte); ok {
return errors.New("val must string") item.Value = v
} else if str, ok := val.(string); ok {
item.Value = []byte(str)
} else {
return errors.New("val only support string and []byte")
} }
item := memcache.Item{Key: key, Value: []byte(v), Expiration: int32(timeout / time.Second)}
return rc.conn.Set(&item) return rc.conn.Set(&item)
} }