-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathtypes_cache.go
92 lines (71 loc) · 1.57 KB
/
types_cache.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
80
81
82
83
84
85
86
87
88
89
90
91
92
package grpcall
import (
"fmt"
"sync"
"time"
"github.com/golang/protobuf/proto"
)
var (
nullTypes = ReqRespTypes{}
)
type ReqRespTypes struct {
reqType proto.Message
respType proto.Message
lastUpdateTime time.Time
}
func (p *ReqRespTypes) isExpired(interval time.Duration) bool {
if time.Now().Before(p.lastUpdateTime.Add(interval)) {
return true
}
return false
}
type protoTypesCache struct {
cache sync.Map
syncInterval time.Duration
}
func newProtoTypeCache() *protoTypesCache {
p := &protoTypesCache{}
p.init()
return p
}
func (p *protoTypesCache) init() {
p.cache = sync.Map{}
}
func (p *protoTypesCache) get(fmth string) (ReqRespTypes, bool) {
model, ok := p.cache.Load(fmth)
if !ok {
return nullTypes, false
}
return model.(ReqRespTypes), ok
}
func (p *protoTypesCache) getRequestType(fmth string) (proto.Message, bool) {
model, ok := p.cache.Load(fmth)
if !ok {
return nil, false
}
return model.(proto.Message), ok
}
func (p *protoTypesCache) getRespType(fmth string) (proto.Message, bool) {
model, ok := p.cache.Load(fmth)
if !ok {
return nil, false
}
return model.(proto.Message), ok
}
func (p *protoTypesCache) set(fmth string, reqType, respType proto.Message) error {
p.cache.Store(fmth, ReqRespTypes{
reqType: reqType,
respType: respType,
lastUpdateTime: time.Now(),
})
return nil
}
func (p *protoTypesCache) reset() {
p.cache = sync.Map{}
}
func (p *protoTypesCache) makeKey(svc, mth string) string {
return fmt.Sprintf("%s/%s", svc, mth)
}
func (p *protoTypesCache) clean() {
p.cache = sync.Map{}
}