github地址:https://github.com/hackssssss/lru_expired_cache
之前实现了lru算法的cache,链接,后来发现可以添加key自动过期的策略,采用惰性过期策略。即当get或者set这个key时,才去更新key的状态,如果过期,那么将其删除。
package lru_expiredcache
import (
"container/list"
"fmt"
"sync"
"time"
)
type value struct {
data []byte
lruPos *list.Element
expiredTime int64
}
type lruExpiredCache struct {
maxSize int
data map[interface{}]*value
lck *sync.Mutex
lru *list.List
}
func NewCache(maxLength int) *lruExpiredCache {
if maxLength <= 0 {
panic("maxLength can not < 0 in NewCache")
}
return &lruExpiredCache{
maxSize: maxLength,
data: make(map[interface{}]*value),
lck: new(sync.Mutex),
lru: list.New(),
}
}
func (c *lruExpiredCache) Set(key interface{}, data []byte) {
c.lck.Lock()
defer c.lck.Unlock()
/