actor.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. package sessions
  2. import (
  3. "context"
  4. redisComponent "f1-game/internal/component/redis"
  5. nameActor "f1-game/internal/name/actor"
  6. nameRemote "f1-game/internal/name/remote"
  7. "f1-game/internal/pb"
  8. "fmt"
  9. "sync/atomic"
  10. "time"
  11. cstring "github.com/cherry-game/cherry/extend/string"
  12. clog "github.com/cherry-game/cherry/logger"
  13. "github.com/cherry-game/cherry/net/parser/pomelo"
  14. cproto "github.com/cherry-game/cherry/net/proto"
  15. cprofile "github.com/cherry-game/cherry/profile"
  16. "github.com/go-redis/redis/v8"
  17. "github.com/goburrow/cache"
  18. )
  19. var (
  20. actor = &Actor{}
  21. )
  22. type (
  23. Actor struct {
  24. pomelo.ActorBase
  25. isSync bool // 是否实时同步标识
  26. cache cache.Cache // session cache. key:playeID, value:*cproto.Session
  27. count int64 // session count
  28. redisClient *redis.Client // redis client
  29. ctx context.Context // context
  30. redisFields []string // redis查询的字段
  31. redisKeyFormat string // redis key
  32. onbindFuncList []OnBindFunc // 绑定触发函数
  33. onUnbindFuncList []OnUnbindFunc // 解绑触发函数
  34. }
  35. OnBindFunc func(session *cproto.Session) bool
  36. OnUnbindFunc func(playerID int64)
  37. )
  38. // isSync = true 则实时同步session到本地进程
  39. func NewActor(isSync bool) *Actor {
  40. actor.isSync = isSync
  41. actor.ctx = context.Background()
  42. actor.redisFields = []string{
  43. UID,
  44. SID,
  45. AgentPath,
  46. }
  47. actor.redisKeyFormat = fmt.Sprintf("%s-game:session:", cprofile.Env())
  48. actor.cache = buildCache(isSync, 100000, 1*time.Second)
  49. actor.count = 0
  50. return actor
  51. }
  52. func (p *Actor) AliasID() string {
  53. return nameActor.GateSessions
  54. }
  55. func (p *Actor) OnInit() {
  56. if p.isSync {
  57. p.Remote().Register(nameRemote.Sessions_Bind, p.bind)
  58. p.Remote().Register(nameRemote.Sessions_Unbind, p.ubind)
  59. }
  60. // 初始化redis
  61. p.initRedis()
  62. clog.Infof("[sessions] actor init success. isSync = %v", p.isSync)
  63. }
  64. func (p *Actor) bind(session *cproto.Session) {
  65. playerID := GetPlayerID(session)
  66. if playerID > 0 {
  67. p.addSession2Cache(playerID, session)
  68. for _, fn := range p.onbindFuncList {
  69. fn(session)
  70. }
  71. }
  72. }
  73. func (p *Actor) ubind(req *pb.I64) {
  74. if req.Value > 0 {
  75. p.delSessoin2Cache(req.Value)
  76. for _, fn := range p.onUnbindFuncList {
  77. fn(req.Value)
  78. }
  79. }
  80. }
  81. func (p *Actor) initRedis() {
  82. config := cprofile.GetConfig("sessions")
  83. if config.LastError() != nil {
  84. clog.Fatal("sessions property not exists.")
  85. return
  86. }
  87. redisID := config.GetString("redis_id")
  88. if redisID == "" {
  89. clog.Fatal("sessions redis_id property not exists.")
  90. return
  91. }
  92. redisConfigList := cprofile.GetConfig("redis")
  93. if redisConfigList.LastError() != nil {
  94. clog.Fatal("redis property not exists.")
  95. return
  96. }
  97. redisConfig := redisComponent.GetConfigWithRedisID(redisConfigList, redisID)
  98. if redisConfig == nil {
  99. clog.Fatalf("redis config not found. [redisID = %s]", redisID)
  100. return
  101. }
  102. _, options := redisComponent.NewClientOption(redisConfig)
  103. p.redisClient = redis.NewClient(options)
  104. }
  105. func (p *Actor) BuildPlayerKey(playerID int64) string {
  106. return fmt.Sprintf("%s%d", p.redisKeyFormat, playerID)
  107. }
  108. func (p *Actor) GetCacheSession(playerID int64) (*cproto.Session, bool) {
  109. value, found := p.cache.GetIfPresent(playerID)
  110. if !found {
  111. return nil, false
  112. }
  113. return value.(*cproto.Session), true
  114. }
  115. func (p *Actor) GetCacheSessions(playerIDS []int64) (map[int64]*cproto.Session, []int64) {
  116. var (
  117. sessionMaps = map[int64]*cproto.Session{}
  118. missPlayerIDS []int64
  119. )
  120. for _, playerID := range playerIDS {
  121. if session, found := p.GetCacheSession(playerID); found {
  122. sessionMaps[playerID] = session
  123. } else {
  124. if playerID > 0 {
  125. missPlayerIDS = append(missPlayerIDS, playerID)
  126. }
  127. }
  128. }
  129. return sessionMaps, missPlayerIDS
  130. }
  131. func (p *Actor) GetRedisSession(playerID int64) (*cproto.Session, bool) {
  132. key := p.BuildPlayerKey(playerID)
  133. result, err := p.redisClient.HMGet(p.ctx, key, p.redisFields...).Result()
  134. if err != nil {
  135. clog.Errorf("[GetRedisSession] error: %v", err)
  136. return nil, false
  137. }
  138. session := result2Session(result)
  139. if len(session.AgentPath) > 0 {
  140. p.addSession2Cache(playerID, session) // add session to cache
  141. return session, true
  142. }
  143. return nil, false
  144. }
  145. func (p *Actor) GetRedisSessions(playerIDS []int64) map[int64]*cproto.Session {
  146. pipeline := p.redisClient.Pipeline()
  147. defer pipeline.Close()
  148. cmds := make([]*redis.SliceCmd, 0, len(playerIDS))
  149. for _, playerID := range playerIDS {
  150. key := p.BuildPlayerKey(playerID)
  151. cmds = append(cmds, pipeline.HMGet(p.ctx, key, p.redisFields...))
  152. }
  153. if _, err := pipeline.Exec(p.ctx); err != nil {
  154. clog.Errorf("[GetRedisSessions] error: %v", err)
  155. return nil
  156. }
  157. sessionMap := map[int64]*cproto.Session{}
  158. for i, playerID := range playerIDS {
  159. result, err := cmds[i].Result()
  160. if err != nil {
  161. continue
  162. }
  163. session := result2Session(result)
  164. if len(session.AgentPath) > 0 && session.Uid > 0 {
  165. p.addSession2Cache(playerID, session) // add session to cache
  166. sessionMap[playerID] = session
  167. }
  168. }
  169. return sessionMap
  170. }
  171. // 设置session绑定时触发的函数
  172. func SetOnBindFunc(fn OnBindFunc) {
  173. if fn != nil {
  174. actor.onbindFuncList = append(actor.onbindFuncList, fn)
  175. }
  176. }
  177. // 设置session解绑时触发的函数
  178. func SetOnUnbindFunc(fn OnUnbindFunc) {
  179. if fn != nil {
  180. actor.onUnbindFuncList = append(actor.onUnbindFuncList, fn)
  181. }
  182. }
  183. func buildCache(isSync bool, maxSize int, expire time.Duration) cache.Cache {
  184. var options []cache.Option
  185. if !isSync {
  186. // 非实时同步模式,缓存后x秒过期
  187. options = append(options, cache.WithExpireAfterWrite(expire))
  188. }
  189. // 缓存最多10万个session
  190. options = append(options, cache.WithMaximumSize(maxSize))
  191. // 缓存失效时触发监听函数
  192. options = append(options, cache.WithRemovalListener(func(key cache.Key, _ cache.Value) {
  193. // playerID := key.(int64)
  194. // session数量-1
  195. atomic.AddInt64(&actor.count, -1)
  196. }))
  197. return cache.New(options...)
  198. }
  199. func result2Session(result []interface{}) *cproto.Session {
  200. uid := cstring.ToInt64D(cstring.ToString(result[0]), 0)
  201. sid := cstring.ToString(result[1])
  202. agentPath := cstring.ToString(result[2])
  203. return &cproto.Session{
  204. Uid: uid,
  205. Sid: sid,
  206. AgentPath: agentPath,
  207. }
  208. }
  209. func (p *Actor) addSession2Cache(playerID int64, session *cproto.Session) {
  210. p.cache.Put(playerID, session)
  211. atomic.AddInt64(&p.count, 1)
  212. }
  213. func (p *Actor) delSessoin2Cache(playerID int64) {
  214. p.cache.Invalidate(playerID)
  215. }