hotime/cache_memory.go

142 lines
2.2 KiB
Go
Raw Normal View History

2017-08-04 08:20:59 +00:00
package hotime
import (
"time"
2018-04-03 17:54:27 +00:00
"sync"
2018-04-09 17:16:24 +00:00
"strings"
2017-08-04 08:20:59 +00:00
)
type CacheMemory struct {
Time int64
Map
2017-08-23 07:35:49 +00:00
contextBase
2018-04-03 17:54:27 +00:00
mutex *sync.RWMutex
2017-08-04 08:20:59 +00:00
}
//获取Cache键只能为string类型
func (this *CacheMemory) get(key string) interface{} {
this.Error.SetError(nil)
2017-08-23 02:05:47 +00:00
if this.Map[key] == nil {
2017-08-04 08:20:59 +00:00
return nil
}
data := this.Map.Get(key, &this.Error).(cacheData)
if this.GetError() != nil {
return nil
}
//data:=cacheMap[key];
if data.time <= time.Now().Unix() {
delete(this.Map, key)
return nil
}
return data.data
}
2018-04-04 18:44:00 +00:00
func (this *CacheMemory)refreshMap(){
go func() {
this.mutex.Lock()
defer this.mutex.Unlock()
for key,v:=range this.Map{
data:=v.(cacheData)
if data.time <= time.Now().Unix() {
delete(this.Map, key)
}
}
}()
}
2017-08-04 08:20:59 +00:00
//key value ,时间为时间戳
func (this *CacheMemory) set(key string, value interface{}, time int64) {
this.Error.SetError(nil)
var data cacheData
dd := this.Map.Get(key, &this.Error)
if dd == nil {
data = cacheData{}
} else {
data = dd.(cacheData)
}
data.time = time
data.data = value
2017-08-23 02:05:47 +00:00
if this.Map == nil {
this.Map = Map{}
2017-08-04 08:20:59 +00:00
}
2017-08-23 02:05:47 +00:00
this.Map.Put(key, data)
2017-08-04 08:20:59 +00:00
}
func (this *CacheMemory) delete(key string) {
2018-04-09 17:16:24 +00:00
del:=strings.Index(key,"*")
//如果通配删除
if del!=-1{
key=Substr(key,0,del)
for k,_:=range this.Map{
if strings.Index(k,key)!=-1{
delete(this.Map, key)
}
}
}else{
delete(this.Map, key)
}
2017-08-04 08:20:59 +00:00
}
func (this *CacheMemory) Cache(key string, data ...interface{}) *Obj {
2018-04-04 18:44:00 +00:00
x:=RandX(1,100000)
if x>99950{
this.refreshMap()
}
2018-04-03 17:54:27 +00:00
if this.mutex==nil{
this.mutex=&sync.RWMutex{}
}
2018-04-03 19:11:51 +00:00
reData:= &Obj{}
2018-04-03 17:54:27 +00:00
2017-08-04 08:20:59 +00:00
if len(data) == 0 {
2018-04-03 19:11:51 +00:00
this.mutex.RLock()
reData.Data=this.get(key)
this.mutex.RUnlock()
return reData
2017-08-04 08:20:59 +00:00
}
tim := time.Now().Unix()
if len(data) == 1 && data[0] == nil {
2018-04-03 19:11:51 +00:00
this.mutex.Lock()
2017-08-04 08:20:59 +00:00
this.delete(key)
2018-04-03 19:11:51 +00:00
this.mutex.Unlock()
return reData
2017-08-04 08:20:59 +00:00
}
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
}
}
2018-04-03 19:11:51 +00:00
this.mutex.Lock()
2017-08-04 08:20:59 +00:00
this.set(key, data[0], tim)
2018-04-03 19:11:51 +00:00
this.mutex.Unlock()
return reData
2017-08-04 08:20:59 +00:00
}