github.com/vicanso/lru-ttl@v1.5.1/ring.go (about) 1 // Copyright 2021 tree xie 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package lruttl 16 17 import "time" 18 19 type ringCache struct { 20 // lru cache list 21 lruCaches []*Cache 22 size int 23 } 24 25 type RingCacheParams struct { 26 // ring size 27 Size int 28 // max entries 29 MaxEntries int 30 // default ttl 31 DefaultTTL time.Duration 32 } 33 34 // NewRing returns a new ring cache 35 func NewRing(params RingCacheParams, opts ...CacheOption) *ringCache { 36 if params.DefaultTTL <= 0 || params.Size <= 0 || params.MaxEntries <= params.Size { 37 panic("default ttl, size and max entries must be gt 0") 38 } 39 lruCacheCount := params.MaxEntries/params.Size + 1 40 lruCaches := make([]*Cache, params.Size) 41 for i := 0; i < params.Size; i++ { 42 lruCaches[i] = New(lruCacheCount, params.DefaultTTL, opts...) 43 } 44 return &ringCache{ 45 lruCaches: lruCaches, 46 size: params.Size, 47 } 48 } 49 50 // Get returns the lru ttl cache by key 51 func (rc *ringCache) Get(key string) *Cache { 52 value := MemHashString(key) 53 index := int(value % uint64(rc.size)) 54 return rc.lruCaches[index] 55 }