12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 |
- package main
- import (
- "sync"
- "time"
- )
- type tokenItem struct {
- Content []byte
- Timestamp int64
- }
- type MemoryStore struct {
- Map sync.Map
- Svr *TcpServer
- }
- func NewMemoryStore() *MemoryStore {
- ms := &MemoryStore{}
- ms.startRefresh()
- return ms
- }
- // 设置
- func (this* MemoryStore)Set(key string, bytess []byte) {
- this.Map.Store(key, &tokenItem{
- Content: bytess,
- Timestamp: time.Now().Unix(),
- })
- }
- // 移除
- func (this* MemoryStore)Remove(key string) {
- this.Map.Delete(key)
- }
- // 所有内容列表
- func (this *MemoryStore)All()map[string][]byte{
- mmap := make(map[string][]byte)
- this.Map.Range(func(k, v interface{})bool{
- ti := v.(*tokenItem)
- mmap[k.(string)] = ti.Content
- return true
- })
- return mmap
- }
- // 刷新
- func (this *MemoryStore)startRefresh(){
- go func() {
- // 两天检查一下
- ticket := time.NewTicker(time.Hour * 24 * 30)
- for {
- select {
- case <-ticket.C:
- keys := make([]string, 0)
- this.Map.Range(func(k, v interface{}) bool {
- item := v.(*tokenItem)
- if time.Now().Sub(time.Unix(item.Timestamp, 0)).Hours() > 24{
- // 大于两天
- keys = append(keys, k.(string))
- }
- return true
- })
- for i := range keys{
- if _, ok := this.Map.Load(keys[i]); ok{
- this.Svr.Broadcast("","remove", []byte(keys[i]))
- }
- this.Map.Delete(keys[i])
- }
- }
- }
- }()
- }
|