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

147 lines
2.6 KiB
Go

1 year ago
package core
import (
1 year ago
"git.noahlan.cn/noahlan/nnet/entity"
"sync"
"sync/atomic"
)
1 year ago
type session struct {
sync.RWMutex // 数据锁
1 year ago
// 网络单元
entity entity.NetworkEntity
id int64 // Session全局唯一ID
uid string // 用户ID不绑定的情况下与sid一致
data map[string]interface{} // session数据存储内存
}
func newSession(entity entity.NetworkEntity, id int64) *session {
1 year ago
return &session{
id: id,
1 year ago
entity: entity,
uid: "",
data: make(map[string]interface{}),
}
}
1 year ago
// ID 获取 session ID
func (s *session) ID() int64 {
return s.id
}
1 year ago
// UID 获取UID
func (s *session) UID() string {
return s.uid
}
1 year ago
// Bind 绑定uid
func (s *session) Bind(uid string) {
s.uid = uid
}
1 year ago
// Attribute 获取指定key对应参数
func (s *session) Attribute(key string) interface{} {
s.RLock()
defer s.RUnlock()
return s.data[key]
}
1 year 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
}
1 year ago
// Exists 指定key是否存在
func (s *session) Exists(key string) bool {
s.RLock()
defer s.RUnlock()
_, has := s.data[key]
return has
}
1 year ago
// Attributes 获取所有参数
func (s *session) Attributes() map[string]interface{} {
s.RLock()
defer s.RUnlock()
return s.data
}
1 year ago
// RemoveAttribute 移除指定key对应参数
func (s *session) RemoveAttribute(key string) {
s.Lock()
defer s.Unlock()
delete(s.data, key)
}
1 year ago
// SetAttribute 设置参数
func (s *session) SetAttribute(key string, value interface{}) {
s.Lock()
defer s.Unlock()
s.data[key] = value
}
1 year ago
// Invalidate 清理
func (s *session) Invalidate() {
s.Lock()
defer s.Unlock()
s.id = 0
s.uid = ""
s.data = make(map[string]interface{})
}
1 year ago
// Close 关闭
func (s *session) Close() {
//s.entity.Close()
s.Invalidate()
}
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)
}