-
Notifications
You must be signed in to change notification settings - Fork 147
/
reuse_msg.go
79 lines (65 loc) · 1.71 KB
/
reuse_msg.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// Copyright (c) 2018 The MATRIX Authors
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php
package common
import (
"errors"
"time"
)
var (
ErrMsgExist = errors.New("msg already exist")
ErrMsgNotExist = errors.New("msg not exist")
ErrUseMsgTooOften = errors.New("use msg too often, please try later")
)
type msgCache struct {
msg interface{}
useTime int64
}
type ReuseMsgController struct {
msgMap map[Hash]*msgCache
useInterval int64
}
func NewReuseMsgController(useInterval int64) *ReuseMsgController {
return &ReuseMsgController{
msgMap: make(map[Hash]*msgCache),
useInterval: useInterval,
}
}
func (self ReuseMsgController) IsExistMsg(msgKey Hash) bool {
_, exist := self.msgMap[msgKey]
return exist
}
func (self ReuseMsgController) AddMsg(msgKey Hash, msg interface{}, lastUseTime int64) error {
if self.IsExistMsg(msgKey) {
return ErrMsgExist
}
self.msgMap[msgKey] = &msgCache{msg: msg, useTime: lastUseTime}
return nil
}
func (self ReuseMsgController) GetMsgList() []interface{} {
result := make([]interface{}, 0)
for _, value := range self.msgMap {
result = append(result, value.msg)
}
return result
}
func (self ReuseMsgController) GetMsgByKey(msgKey Hash) interface{} {
cache, exist := self.msgMap[msgKey]
if !exist {
return nil
} else {
return cache.msg
}
}
func (self ReuseMsgController) ReUseMsg(msgKey Hash) (interface{}, error) {
cache, exist := self.msgMap[msgKey]
if !exist {
return nil, ErrMsgNotExist
}
curTime := time.Now().Unix()
if curTime-cache.useTime < self.useInterval {
return nil, ErrUseMsgTooOften
}
cache.useTime = curTime
return cache.msg, nil
}