history.go 1.9 KB

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