This commit is contained in:
Vendored
+124
@@ -0,0 +1,124 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"time"
|
||||
"github.com/garyburd/redigo/redis"
|
||||
. "go.hoteas.com/hotime"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type CacheRedis struct {
|
||||
Host string
|
||||
Pwd string
|
||||
Time int64
|
||||
conn redis.Conn
|
||||
tag int64
|
||||
Error
|
||||
}
|
||||
|
||||
//唯一标志
|
||||
func (this *CacheRedis) GetTag() int64 {
|
||||
|
||||
if this.tag == int64(0) {
|
||||
this.tag = time.Now().UnixNano()
|
||||
}
|
||||
return this.tag
|
||||
}
|
||||
|
||||
func (this *CacheRedis) reCon()bool{
|
||||
var err error
|
||||
this.conn,err=redis.Dial("tcp",this.Host)
|
||||
if err!=nil{
|
||||
this.conn=nil
|
||||
this.Error.SetError(err)
|
||||
return false
|
||||
}
|
||||
|
||||
_,err=this.conn.Do("AUTH",this.Pwd)
|
||||
if err!=nil{
|
||||
this.conn=nil
|
||||
this.Error.SetError(err)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (this *CacheRedis) Cache(key string, data ...interface{}) *Obj {
|
||||
reData:= &Obj{}
|
||||
var err error
|
||||
if this.conn==nil{
|
||||
re:=this.reCon()
|
||||
if !re{
|
||||
return reData
|
||||
}
|
||||
}
|
||||
//查询缓存
|
||||
if len(data) == 0 {
|
||||
|
||||
reData.Data, err = redis.String(this.conn.Do("GET", key))
|
||||
if err != nil {
|
||||
reData.Data=nil
|
||||
if !strings.Contains(err.Error(), "nil returned") {
|
||||
this.Error.SetError(err)
|
||||
_, err = this.conn.Do("PING")
|
||||
if err != nil {
|
||||
if this.reCon() {
|
||||
reData.Data, err = redis.String(this.conn.Do("GET", key))
|
||||
}
|
||||
}
|
||||
|
||||
return reData
|
||||
}
|
||||
}
|
||||
return reData
|
||||
|
||||
}
|
||||
tim := int64(0)
|
||||
//删除缓存
|
||||
if len(data) == 1 && data[0] == nil {
|
||||
|
||||
_,err=this.conn.Do("DEL",key)
|
||||
if err!=nil{
|
||||
this.Error.SetError(err)
|
||||
_,err=this.conn.Do("PING")
|
||||
if err!=nil{
|
||||
if this.reCon(){
|
||||
_,err=this.conn.Do("DEL",key)
|
||||
}
|
||||
}
|
||||
}
|
||||
return reData
|
||||
}
|
||||
//添加缓存
|
||||
if len(data) == 1 {
|
||||
|
||||
if this.Time == 0 {
|
||||
this.Time = Config.GetInt64("cacheShortTime")
|
||||
}
|
||||
|
||||
tim += this.Time
|
||||
}
|
||||
if len(data) == 2 {
|
||||
this.Error.SetError(nil)
|
||||
tempt := ObjToInt64(data[1], &this.Error)
|
||||
if this.GetError() == nil {
|
||||
|
||||
tim = tim + tempt
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
_,err=this.conn.Do("SET",key,ObjToStr(data[0]),"EX",ObjToStr(tim))
|
||||
if err!=nil{
|
||||
|
||||
this.Error.SetError(err)
|
||||
_,err=this.conn.Do("PING")
|
||||
if err!=nil{
|
||||
if this.reCon(){
|
||||
_,err=this.conn.Do("SET",key,ObjToStr(data[0]),"EX",ObjToStr(tim))
|
||||
}
|
||||
}
|
||||
}
|
||||
return reData
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user