/
client_cache.go
55 lines (44 loc) · 1.2 KB
/
client_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
package v2
import (
"crypto/rand"
"math/big"
"time"
"github.com/jellydator/ttlcache/v3"
)
type ClientCache interface {
GetClient(key string) Client
AddClient(key string, client Client)
DeleteClient(key string)
}
const (
// TTL is between 23 and 25 hours.
ttlInSecondsLower, ttlInSecondsUpper = 23 * 60 * 60, 25 * 60 * 60
)
type MemoryClientCache struct {
internal ttlcache.Cache[string, Client]
}
func NewMemoryClientCache() *MemoryClientCache {
cache := &MemoryClientCache{internal: *ttlcache.New[string, Client]()}
go cache.internal.Start()
return cache
}
func (m *MemoryClientCache) GetClient(key string) Client {
cachedClient := m.internal.Get(key)
if cachedClient != nil {
return cachedClient.Value()
}
return nil
}
func (m *MemoryClientCache) AddClient(key string, value Client) {
m.internal.Set(key, value, getRandomTTL())
}
func (m *MemoryClientCache) DeleteClient(key string) {
m.internal.Delete(key)
}
func (m *MemoryClientCache) Size() int {
return m.internal.Len()
}
func getRandomTTL() time.Duration {
randomRange, _ := rand.Int(rand.Reader, big.NewInt(int64(ttlInSecondsUpper-ttlInSecondsLower)))
return time.Duration(randomRange.Int64()+int64(ttlInSecondsLower)) * time.Second
}