| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697 |
- package gold2chipwheel
- import (
- "bet24.com/log"
- "bet24.com/redis"
- item "bet24.com/servers/micros/item_inventory/proto"
- "encoding/json"
- "sync"
- "time"
- )
- const max_history = 20
- type historyInfo struct {
- Bet int `json:"c"`
- Items []item.ItemPack `json:"i"`
- Time int64 `json:"t"` // time stamp,前端需自行转换显示
- }
- type historymanager struct {
- lock *sync.RWMutex
- isDirty bool
- records map[int][]historyInfo
- }
- func newHistoryManager() *historymanager {
- ret := new(historymanager)
- ret.ctor()
- return ret
- }
- func (hm *historymanager) ctor() {
- hm.lock = &sync.RWMutex{}
- hm.records = make(map[int][]historyInfo)
- hm.loadHistory()
- hm.flush()
- }
- func (hm *historymanager) getHistory(userId int) string {
- hm.lock.RLock()
- u, ok := hm.records[userId]
- hm.lock.RUnlock()
- if !ok {
- return ""
- }
- d, _ := json.Marshal(u)
- return string(d)
- }
- func (hm *historymanager) addHistory(userId int, bet int, items []item.ItemPack) {
- h := historyInfo{
- //UserId: userId,
- Bet: bet,
- Items: items,
- Time: time.Now().Unix(),
- }
- hm.lock.Lock()
- hm.records[userId] = append(hm.records[userId], h)
- count := len(hm.records[userId]) - max_history
- if count > 0 {
- hm.records[userId] = hm.records[userId][count:]
- }
- hm.lock.Unlock()
- hm.isDirty = true
- }
- func getHistoryRedisKey() string {
- return "gold2chipwheel:history"
- }
- func (hm *historymanager) loadHistory() {
- data, ok := redis.String_Get(getHistoryRedisKey())
- if data == "" || !ok {
- return
- }
- hm.lock.Lock()
- err := json.Unmarshal([]byte(data), &hm.records)
- hm.lock.Unlock()
- if err != nil {
- log.Release("historymanager.loadHistory Unmarshal failed err:%v,%s", err, data)
- return
- }
- }
- func (hm *historymanager) flush() {
- time.AfterFunc(refresh_config_sec*time.Second, hm.flush)
- hm.lock.RLock()
- if !hm.isDirty {
- hm.lock.RUnlock()
- return
- }
- hm.isDirty = false
- d, _ := json.Marshal(hm.records)
- hm.lock.RUnlock()
- go redis.String_Set(getHistoryRedisKey(), string(d))
- }
|