forked from dunglas/mercure
-
Notifications
You must be signed in to change notification settings - Fork 0
/
topic_selector_lru.go
49 lines (37 loc) · 1.2 KB
/
topic_selector_lru.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
package mercure
import (
"hash/fnv"
lru "github.com/hashicorp/golang-lru"
)
// Gather stats to find the best default values.
const (
DefaultTopicSelectorStoreLRUMaxEntriesPerShard = int64(1e4)
DefaultTopicSelectorStoreLRUShardCount = int64(256) // 2.5 million entries.
)
// NewTopicSelectorStoreLRU creates a TopicSelectorStore with an LRU cache.
func NewTopicSelectorStoreLRU(maxEntriesPerShard, shardCount int64) (*TopicSelectorStore, error) {
if maxEntriesPerShard == 0 {
return &TopicSelectorStore{}, nil
}
if shardCount == 0 {
shardCount = DefaultTopicSelectorStoreLRUShardCount
}
lruMap := make(shardedLRUCache, shardCount)
for i := 0; i < int(shardCount); i++ {
lruMap[i], _ = lru.New(int(maxEntriesPerShard))
}
return &TopicSelectorStore{cache: &lruMap, skipSelect: true}, nil
}
type shardedLRUCache map[int]*lru.Cache
func (c *shardedLRUCache) Get(k string) (interface{}, bool) {
return c.getShard(k).Get(k)
}
func (c *shardedLRUCache) Set(k string, v interface{}, _ int64) bool {
c.getShard(k).Add(k, v)
return true
}
func (c *shardedLRUCache) getShard(k interface{}) *lru.Cache {
h := fnv.New32a()
_, _ = h.Write([]byte(k.(string)))
return (*c)[int(h.Sum32())%len(*c)]
}