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

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

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