You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
nnet/core/session.go

149 lines
2.6 KiB
Go

2 years ago
package core
import (
2 years ago
"git.noahlan.cn/noahlan/nnet/entity"
"sync"
"sync/atomic"
)
2 years ago
type session struct {
sync.RWMutex // 数据锁
2 years ago
// 网络单元
entity entity.NetworkEntity
id int64 // Session全局唯一ID
uid string // 用户ID不绑定的情况下与sid一致
data map[string]interface{} // session数据存储内存
}
2 years ago
func newSession(entity entity.NetworkEntity) *session {
return &session{
id: sessionIDMgrInstance.SessionID(),
entity: entity,
uid: "",
data: make(map[string]interface{}),
}
}
2 years ago
// ID 获取 session ID
func (s *session) ID() int64 {
return s.id
}
2 years ago
// UID 获取UID
func (s *session) UID() string {
return s.uid
}
2 years ago
// Bind 绑定uid
func (s *session) Bind(uid string) {
s.uid = uid
}
2 years ago
// Attribute 获取指定key对应参数
func (s *session) Attribute(key string) interface{} {
s.RLock()
defer s.RUnlock()
return s.data[key]
}
2 years ago
// Keys 获取所有参数key
func (s *session) Keys() []string {
s.RLock()
defer s.RUnlock()
keys := make([]string, 0, len(s.data))
for k := range s.data {
keys = append(keys, k)
}
return keys
}
2 years ago
// Exists 指定key是否存在
func (s *session) Exists(key string) bool {
s.RLock()
defer s.RUnlock()
_, has := s.data[key]
return has
}
2 years ago
// Attributes 获取所有参数
func (s *session) Attributes() map[string]interface{} {
s.RLock()
defer s.RUnlock()
return s.data
}
2 years ago
// RemoveAttribute 移除指定key对应参数
func (s *session) RemoveAttribute(key string) {
s.Lock()
defer s.Unlock()
delete(s.data, key)
}
2 years ago
// SetAttribute 设置参数
func (s *session) SetAttribute(key string, value interface{}) {
s.Lock()
defer s.Unlock()
s.data[key] = value
}
2 years ago
// Invalidate 清理
func (s *session) Invalidate() {
s.Lock()
defer s.Unlock()
s.id = 0
s.uid = ""
s.data = make(map[string]interface{})
}
2 years ago
// Close 关闭
func (s *session) Close() {
//s.entity.Close()
s.Invalidate()
}
var sessionIDMgrInstance = newSessionIDMgr()
type sessionIDMgr struct {
count int64
sid int64
}
func newSessionIDMgr() *sessionIDMgr {
return &sessionIDMgr{}
}
// Increment the connection count
func (c *sessionIDMgr) Increment() {
atomic.AddInt64(&c.count, 1)
}
// Decrement the connection count
func (c *sessionIDMgr) Decrement() {
atomic.AddInt64(&c.count, -1)
}
// Count returns the connection numbers in current
func (c *sessionIDMgr) Count() int64 {
return atomic.LoadInt64(&c.count)
}
// Reset the connection service status
func (c *sessionIDMgr) Reset() {
atomic.StoreInt64(&c.count, 0)
atomic.StoreInt64(&c.sid, 0)
}
// SessionID returns the session id
func (c *sessionIDMgr) SessionID() int64 {
return atomic.AddInt64(&c.sid, 1)
}