hotime/session.go

84 lines
1.7 KiB
Go
Raw Permalink Normal View History

2017-08-04 08:20:59 +00:00
package hotime
2021-05-24 07:27:41 +08:00
import (
2022-03-13 01:12:29 +08:00
. "code.hoteas.com/golang/hotime/cache"
. "code.hoteas.com/golang/hotime/common"
"sync"
2021-05-24 07:27:41 +08:00
)
// session对象
2017-08-04 08:20:59 +00:00
type SessionIns struct {
*HoTimeCache
SessionId string
2017-08-04 08:20:59 +00:00
Map
2021-05-24 07:27:41 +08:00
ContextBase
mutex sync.RWMutex
2017-08-04 08:20:59 +00:00
}
// set 保存 session 到缓存,必须在锁内调用或传入深拷贝的 map
func (that *SessionIns) setWithCopy() {
// 深拷贝 Map 防止并发修改
that.mutex.RLock()
copyMap := make(Map, len(that.Map))
for k, v := range that.Map {
copyMap[k] = v
}
that.mutex.RUnlock()
that.HoTimeCache.Session(HEAD_SESSION_ADD+that.SessionId, copyMap)
2017-08-04 08:20:59 +00:00
}
func (that *SessionIns) Session(key string, data ...interface{}) *Obj {
that.mutex.Lock()
if that.Map == nil {
that.getWithoutLock()
2017-08-04 08:20:59 +00:00
}
that.mutex.Unlock()
2017-08-04 08:20:59 +00:00
2017-08-10 10:14:56 +00:00
if len(data) != 0 {
that.mutex.Lock()
2017-08-10 10:14:56 +00:00
if data[0] == nil {
delete(that.Map, key)
2017-08-10 10:14:56 +00:00
} else {
that.Map[key] = data[0]
2017-08-04 08:20:59 +00:00
}
that.mutex.Unlock()
// 使用深拷贝版本保存,避免并发问题
that.setWithCopy()
2017-08-10 10:14:56 +00:00
return &Obj{Data: nil}
2017-08-04 08:20:59 +00:00
}
that.mutex.RLock()
result := &Obj{Data: that.Map.Get(key)}
that.mutex.RUnlock()
return result
2017-08-04 08:20:59 +00:00
}
// getWithoutLock 内部使用,调用前需要已持有锁
func (that *SessionIns) getWithoutLock() {
that.Map = that.HoTimeCache.Session(HEAD_SESSION_ADD + that.SessionId).ToMap()
if that.Map != nil {
return
2017-08-04 08:20:59 +00:00
}
that.Map = Map{}
// 保存时也需要深拷贝
copyMap := make(Map, len(that.Map))
for k, v := range that.Map {
copyMap[k] = v
}
that.HoTimeCache.Session(HEAD_SESSION_ADD+that.SessionId, copyMap)
}
2017-08-04 08:20:59 +00:00
func (that *SessionIns) get() {
that.mutex.Lock()
defer that.mutex.Unlock()
that.getWithoutLock()
2017-08-04 08:20:59 +00:00
}
func (that *SessionIns) Init(cache *HoTimeCache) {
that.mutex = sync.RWMutex{}
that.HoTimeCache = cache
2017-08-10 10:14:56 +00:00
}