-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache.go
62 lines (54 loc) · 1.2 KB
/
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
package main
import (
"context"
"sync"
"time"
)
var now = time.Now
type serviceInstanceIdPair struct {
serviceId string
instanceId string
}
type sdCacheEntry struct {
e time.Time
sd *ServiceDescriptor
}
type sdCache map[serviceInstanceIdPair]sdCacheEntry
type UplookerCache struct {
mu sync.RWMutex
ttl time.Duration
backingUplooker ServiceUplooker
entries sdCache
}
func NewUplookerCache(backing ServiceUplooker, cacheTtl time.Duration) *UplookerCache {
return &UplookerCache{
ttl: cacheTtl,
backingUplooker: backing,
entries: make(sdCache),
}
}
func (c *UplookerCache) LookupService(ctx context.Context, serviceId, instanceId string) (*ServiceDescriptor, error) {
c.mu.RLock()
t := now()
k := serviceInstanceIdPair{serviceId, instanceId}
if v, ok := c.entries[k]; ok {
if t.Before(v.e) {
c.mu.RUnlock()
return v.sd, nil
}
}
c.mu.RUnlock()
c.mu.Lock()
defer c.mu.Unlock()
if v, ok := c.entries[k]; ok {
if t.Before(v.e) {
return v.sd, nil
}
}
sd, err := c.backingUplooker.LookupService(ctx, serviceId, instanceId)
if err != nil {
return nil, err
}
c.entries[k] = sdCacheEntry{t.Add(c.ttl), sd}
return sd, nil
}