netramesh
192 строки · 4.5 Кб
1package cache2
3import (4"crypto/rand"5"math"6"math/big"7insecurerand "math/rand"8"os"9"runtime"10"time"11)
12
13// This is an experimental and unexported (for now) attempt at making a cache
14// with better algorithmic complexity than the standard one, namely by
15// preventing write locks of the entire cache when an item is added. As of the
16// time of writing, the overhead of selecting buckets results in cache
17// operations being about twice as slow as for the standard cache with small
18// total cache sizes, and faster for larger ones.
19//
20// See cache_test.go for a few benchmarks.
21
22type unexportedShardedCache struct {23*shardedCache24}
25
26type shardedCache struct {27seed uint3228m uint3229cs []*cache30janitor *shardedJanitor31}
32
33// djb2 with better shuffling. 5x faster than FNV with the hash.Hash overhead.
34func djb33(seed uint32, k string) uint32 {35var (36l = uint32(len(k))37d = 5381 + seed + l38i = uint32(0)39)40// Why is all this 5x faster than a for loop?41if l >= 4 {42for i < l-4 {43d = (d * 33) ^ uint32(k[i])44d = (d * 33) ^ uint32(k[i+1])45d = (d * 33) ^ uint32(k[i+2])46d = (d * 33) ^ uint32(k[i+3])47i += 448}49}50switch l - i {51case 1:52case 2:53d = (d * 33) ^ uint32(k[i])54case 3:55d = (d * 33) ^ uint32(k[i])56d = (d * 33) ^ uint32(k[i+1])57case 4:58d = (d * 33) ^ uint32(k[i])59d = (d * 33) ^ uint32(k[i+1])60d = (d * 33) ^ uint32(k[i+2])61}62return d ^ (d >> 16)63}
64
65func (sc *shardedCache) bucket(k string) *cache {66return sc.cs[djb33(sc.seed, k)%sc.m]67}
68
69func (sc *shardedCache) Set(k string, x interface{}, d time.Duration) {70sc.bucket(k).Set(k, x, d)71}
72
73func (sc *shardedCache) Add(k string, x interface{}, d time.Duration) error {74return sc.bucket(k).Add(k, x, d)75}
76
77func (sc *shardedCache) Replace(k string, x interface{}, d time.Duration) error {78return sc.bucket(k).Replace(k, x, d)79}
80
81func (sc *shardedCache) Get(k string) (interface{}, bool) {82return sc.bucket(k).Get(k)83}
84
85func (sc *shardedCache) Increment(k string, n int64) error {86return sc.bucket(k).Increment(k, n)87}
88
89func (sc *shardedCache) IncrementFloat(k string, n float64) error {90return sc.bucket(k).IncrementFloat(k, n)91}
92
93func (sc *shardedCache) Decrement(k string, n int64) error {94return sc.bucket(k).Decrement(k, n)95}
96
97func (sc *shardedCache) Delete(k string) {98sc.bucket(k).Delete(k)99}
100
101func (sc *shardedCache) DeleteExpired() {102for _, v := range sc.cs {103v.DeleteExpired()104}105}
106
107// Returns the items in the cache. This may include items that have expired,
108// but have not yet been cleaned up. If this is significant, the Expiration
109// fields of the items should be checked. Note that explicit synchronization
110// is needed to use a cache and its corresponding Items() return values at
111// the same time, as the maps are shared.
112func (sc *shardedCache) Items() []map[string]Item {113res := make([]map[string]Item, len(sc.cs))114for i, v := range sc.cs {115res[i] = v.Items()116}117return res118}
119
120func (sc *shardedCache) Flush() {121for _, v := range sc.cs {122v.Flush()123}124}
125
126type shardedJanitor struct {127Interval time.Duration128stop chan bool129}
130
131func (j *shardedJanitor) Run(sc *shardedCache) {132j.stop = make(chan bool)133tick := time.Tick(j.Interval)134for {135select {136case <-tick:137sc.DeleteExpired()138case <-j.stop:139return140}141}142}
143
144func stopShardedJanitor(sc *unexportedShardedCache) {145sc.janitor.stop <- true146}
147
148func runShardedJanitor(sc *shardedCache, ci time.Duration) {149j := &shardedJanitor{150Interval: ci,151}152sc.janitor = j153go j.Run(sc)154}
155
156func newShardedCache(n int, de time.Duration) *shardedCache {157max := big.NewInt(0).SetUint64(uint64(math.MaxUint32))158rnd, err := rand.Int(rand.Reader, max)159var seed uint32160if err != nil {161os.Stderr.Write([]byte("WARNING: go-cache's newShardedCache failed to read from the system CSPRNG (/dev/urandom or equivalent.) Your system's security may be compromised. Continuing with an insecure seed.\n"))162seed = insecurerand.Uint32()163} else {164seed = uint32(rnd.Uint64())165}166sc := &shardedCache{167seed: seed,168m: uint32(n),169cs: make([]*cache, n),170}171for i := 0; i < n; i++ {172c := &cache{173defaultExpiration: de,174items: map[string]Item{},175}176sc.cs[i] = c177}178return sc179}
180
181func unexportedNewSharded(defaultExpiration, cleanupInterval time.Duration, shards int) *unexportedShardedCache {182if defaultExpiration == 0 {183defaultExpiration = -1184}185sc := newShardedCache(shards, defaultExpiration)186SC := &unexportedShardedCache{sc}187if cleanupInterval > 0 {188runShardedJanitor(sc, cleanupInterval)189runtime.SetFinalizer(SC, stopShardedJanitor)190}191return SC192}
193