exchangehistory.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package slotscore
  2. import (
  3. "bet24.com/log"
  4. "bet24.com/redis"
  5. "encoding/json"
  6. "sync"
  7. "time"
  8. )
  9. const max_history = 20
  10. type historyInfo struct {
  11. Chip int `json:"c"`
  12. Time int64 `json:"t"` // time stamp,前端需自行转换显示
  13. }
  14. type historymanager struct {
  15. lock *sync.RWMutex
  16. isDirty bool
  17. records map[int][]historyInfo
  18. }
  19. func newHistoryManager() *historymanager {
  20. ret := new(historymanager)
  21. ret.ctor()
  22. return ret
  23. }
  24. func (hm *historymanager) ctor() {
  25. hm.lock = &sync.RWMutex{}
  26. hm.records = make(map[int][]historyInfo)
  27. hm.loadHistory()
  28. hm.flush()
  29. }
  30. func (hm *historymanager) getHistory(userId int) string {
  31. hm.lock.RLock()
  32. u, ok := hm.records[userId]
  33. hm.lock.RUnlock()
  34. if !ok {
  35. return ""
  36. }
  37. d, _ := json.Marshal(u)
  38. return string(d)
  39. }
  40. func (hm *historymanager) addHistory(userId int, chip int) {
  41. h := historyInfo{
  42. //UserId: userId,
  43. Chip: chip,
  44. Time: time.Now().Unix(),
  45. }
  46. hm.lock.Lock()
  47. hm.records[userId] = append(hm.records[userId], h)
  48. count := len(hm.records[userId]) - max_history
  49. if count > 0 {
  50. hm.records[userId] = hm.records[userId][count:]
  51. }
  52. hm.lock.Unlock()
  53. hm.isDirty = true
  54. }
  55. func getHistoryRedisKey() string {
  56. return "slotscore:history"
  57. }
  58. func (hm *historymanager) loadHistory() {
  59. data, ok := redis.String_Get(getHistoryRedisKey())
  60. if data == "" || !ok {
  61. return
  62. }
  63. hm.lock.Lock()
  64. err := json.Unmarshal([]byte(data), &hm.records)
  65. hm.lock.Unlock()
  66. if err != nil {
  67. log.Release("historymanager.loadHistory Unmarshal failed err:%v,%s", err, data)
  68. return
  69. }
  70. }
  71. func (hm *historymanager) flush() {
  72. time.AfterFunc(refresh_config_sec*time.Second, hm.flush)
  73. hm.lock.RLock()
  74. if !hm.isDirty {
  75. hm.lock.RUnlock()
  76. return
  77. }
  78. hm.isDirty = false
  79. d, _ := json.Marshal(hm.records)
  80. hm.lock.RUnlock()
  81. go redis.String_Set(getHistoryRedisKey(), string(d))
  82. }