guid.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. package redis
  2. import (
  3. "f1-game/internal/data"
  4. nameLua "f1-game/internal/name/lua"
  5. "fmt"
  6. clog "github.com/cherry-game/cherry/logger"
  7. cprofile "github.com/cherry-game/cherry/profile"
  8. )
  9. const (
  10. guidInitValue = 1048576
  11. uidInitValue = 1048576
  12. chatInitValue = 1024
  13. leagueInitValue = 1874
  14. )
  15. type (
  16. guid struct {
  17. *client
  18. guidKey string // 全局 ID
  19. uidKey string // 全局 uid
  20. chatIDKey string // 全局聊天室唯一ID
  21. leagueIDKey string // 全局联盟唯一ID
  22. }
  23. )
  24. func newGUID() *guid {
  25. return &guid{}
  26. }
  27. func (p *guid) setKey() {
  28. prefix := fmt.Sprintf("%s-guid:", cprofile.Env())
  29. p.guidKey = prefix + "guid" // type = string key = guid
  30. p.uidKey = prefix + "uid" // type = string key = uid
  31. p.chatIDKey = prefix + "chat-id" // type = string key = chat-id
  32. p.leagueIDKey = prefix + "league-id" // type = string key = league-id
  33. }
  34. func (p *guid) ConfigID() string {
  35. return "guid_redis_id"
  36. }
  37. func (p *guid) load(client *client) {
  38. p.client = client
  39. p.setKey()
  40. // 检查 guid key
  41. p.checkKey()
  42. }
  43. func (p *guid) checkKey() {
  44. current := p.checkGUID(p.guidKey, guidInitValue)
  45. clog.Infof("check guid. [current = %d]", current)
  46. current = p.checkGUID(p.uidKey, uidInitValue)
  47. clog.Infof("check uid. [current = %d]", current)
  48. current = p.checkGUID(p.chatIDKey, chatInitValue)
  49. clog.Infof("check chatid. [current = %d]", current)
  50. current = p.checkGUID(p.leagueIDKey, leagueInitValue)
  51. clog.Infof("check leagueid. [current = %d]", current)
  52. }
  53. func (p *guid) NewGUID() int64 {
  54. intCmd := p.Incr(p.Context(), p.guidKey)
  55. return intCmd.Val()
  56. }
  57. func (p *guid) NewUID() int64 {
  58. intCmd := p.Incr(p.Context(), p.uidKey)
  59. return intCmd.Val()
  60. }
  61. func (p *guid) NewChatID() int64 {
  62. intCmd := p.Incr(p.Context(), p.chatIDKey)
  63. return intCmd.Val()
  64. }
  65. func (p *guid) NewLeagueID() int64 {
  66. intCmd := p.Incr(p.Context(), p.leagueIDKey)
  67. return intCmd.Val()
  68. }
  69. func (p *guid) checkGUID(key string, initValue int64) int64 {
  70. script, found := data.Lua.Get(nameLua.Check_Guid)
  71. if !found {
  72. return 0
  73. }
  74. cmd := script.Run(p.Context(), p.client, []string{key}, initValue)
  75. result, err := cmd.Result()
  76. if err != nil {
  77. clog.Warnf("checkGUID error. key = %s, initValue = %d, err = %v", key, initValue, err.Error())
  78. return 0
  79. }
  80. return result.(int64)
  81. }