1
0
mirror of https://github.com/astaxie/beego.git synced 2024-12-25 13:10:50 +00:00

align memcache operations with redis

This commit is contained in:
Pengfei Xue 2014-01-09 18:50:30 +08:00
parent a369b15ef2
commit 0b42e5573b

41
cache/memcache.go vendored
View File

@ -21,7 +21,11 @@ func NewMemCache() *MemcacheCache {
// get value from memcache.
func (rc *MemcacheCache) Get(key string) interface{} {
if rc.c == nil {
rc.c = rc.connectInit()
var err error
rc.c, err = rc.connectInit()
if err != nil {
return err
}
}
v, err := rc.c.Get(key)
if err != nil {
@ -39,7 +43,11 @@ func (rc *MemcacheCache) Get(key string) interface{} {
// put value to memcache. only support string.
func (rc *MemcacheCache) Put(key string, val interface{}, timeout int64) error {
if rc.c == nil {
rc.c = rc.connectInit()
var err error
rc.c, err = rc.connectInit()
if err != nil {
return err
}
}
v, ok := val.(string)
if !ok {
@ -55,7 +63,11 @@ func (rc *MemcacheCache) Put(key string, val interface{}, timeout int64) error {
// delete value in memcache.
func (rc *MemcacheCache) Delete(key string) error {
if rc.c == nil {
rc.c = rc.connectInit()
var err error
rc.c, err = rc.connectInit()
if err != nil {
return err
}
}
_, err := rc.c.Delete(key)
return err
@ -76,7 +88,11 @@ func (rc *MemcacheCache) Decr(key string) error {
// check value exists in memcache.
func (rc *MemcacheCache) IsExist(key string) bool {
if rc.c == nil {
rc.c = rc.connectInit()
var err error
rc.c, err = rc.connectInit()
if err != nil {
return false
}
}
v, err := rc.c.Get(key)
if err != nil {
@ -93,7 +109,11 @@ func (rc *MemcacheCache) IsExist(key string) bool {
// clear all cached in memcache.
func (rc *MemcacheCache) ClearAll() error {
if rc.c == nil {
rc.c = rc.connectInit()
var err error
rc.c, err = rc.connectInit()
if err != nil {
return err
}
}
err := rc.c.FlushAll()
return err
@ -109,20 +129,21 @@ func (rc *MemcacheCache) StartAndGC(config string) error {
return errors.New("config has no conn key")
}
rc.conninfo = cf["conn"]
rc.c = rc.connectInit()
if rc.c == nil {
var err error
rc.c, err = rc.connectInit()
if err != nil {
return errors.New("dial tcp conn error")
}
return nil
}
// connect to memcache and keep the connection.
func (rc *MemcacheCache) connectInit() *memcache.Connection {
func (rc *MemcacheCache) connectInit() (*memcache.Connection, error) {
c, err := memcache.Connect(rc.conninfo)
if err != nil {
return nil
return nil, err
}
return c
return c, nil
}
func init() {