package slotscore import ( "bet24.com/log" "bet24.com/redis" "encoding/json" "sync" "time" ) const max_history = 20 type historyInfo struct { Chip int `json:"c"` 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, chip int) { h := historyInfo{ //UserId: userId, Chip: chip, 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 "slotscore: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)) }