center.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. package redis
  2. import (
  3. "f1-game/internal/data"
  4. nameLua "f1-game/internal/name/lua"
  5. "f1-game/internal/pb"
  6. "fmt"
  7. cstring "github.com/cherry-game/cherry/extend/string"
  8. clog "github.com/cherry-game/cherry/logger"
  9. cprofile "github.com/cherry-game/cherry/profile"
  10. )
  11. type (
  12. center struct {
  13. *client
  14. bindUIDKey string // 根据openid获取uid
  15. lastLoginKey string // type:hash 根据pid获取玩家最后登录列表
  16. }
  17. )
  18. func newCenter() *center {
  19. return &center{}
  20. }
  21. func (p *center) setKey() {
  22. prefix := fmt.Sprintf("%s-center:", cprofile.Env())
  23. p.bindUIDKey = prefix + "bind-uid:%d" // type = hash key = bind-uid:{pid} field = openID value = uid
  24. p.lastLoginKey = prefix + "last-login:%d" // center:last-login:{pid} field:openid
  25. }
  26. func (p *center) ConfigID() string {
  27. return "center_redis_id"
  28. }
  29. func (p *center) load(client *client) {
  30. p.client = client
  31. p.setKey()
  32. }
  33. func (p *center) GetUser(pid int32, openID string) int64 {
  34. uidKey := p.buildBindUIDKey(pid)
  35. val, _ := p.HGetString(uidKey, openID)
  36. if cstring.IsBlank(val) {
  37. return -1
  38. }
  39. return cstring.ToInt64D(val)
  40. }
  41. func (p *center) BindUser(pid int32, openID string) (int64, bool) {
  42. if cstring.IsBlank(openID) {
  43. clog.Warnf("[BindUser] OpenID is error. openID = %v", openID)
  44. return 0, false
  45. }
  46. if pid < 1 {
  47. clog.Warnf("[BindUser] PID is error. pid = %v", pid)
  48. return 0, false
  49. }
  50. script, found := data.Lua.Get(nameLua.Bind_Uid)
  51. if !found {
  52. return 0, false
  53. }
  54. var (
  55. bindUidKey = p.buildBindUIDKey(pid)
  56. )
  57. cmd := script.Run(p.Context(), p.Client, []string{GUID.uidKey, bindUidKey}, openID)
  58. result, err := cmd.Result()
  59. if err != nil {
  60. clog.Warnf("[BindUser] error. err = %v", err.Error())
  61. return 0, false
  62. }
  63. return result.(int64), true
  64. }
  65. func (p *center) buildBindUIDKey(pid int32) string {
  66. return fmt.Sprintf(p.bindUIDKey, pid)
  67. }
  68. func (p *center) GetLastLoginPlayer(pid int32, openID string) []*pb.LastPlayer {
  69. key := p.BuildLastLoginKey(pid)
  70. var list []*pb.LastPlayer
  71. err := p.HGetJSON(key, openID, &list)
  72. if err != nil {
  73. clog.Warnf("pid = %d, openID = %s, err = %v", pid, openID, err)
  74. }
  75. return list
  76. }
  77. func (p *center) BuildLastLoginKey(pid int32) string {
  78. return fmt.Sprintf(p.lastLoginKey, pid)
  79. }