緩存文件置換機(jī)制是計(jì)算機(jī)處理緩存存儲(chǔ)器的一種機(jī)制。
計(jì)算機(jī)存儲(chǔ)器空間的大小固定,無(wú)法容納服務(wù)器上所有的文件,所以當(dāng)有新的文件要被置換入緩存時(shí),必須根據(jù)一定的原則來(lái)取代掉適當(dāng)?shù)奈募4嗽瓌t即所謂緩存文件置換機(jī)制。
緩存文件置換方法有:
- 先進(jìn)先出算法(FIFO):最先進(jìn)入的內(nèi)容作為替換對(duì)象
- 最近最少使用算法(LFU):最近最少使用的內(nèi)容作為替換對(duì)象
- 最久未使用算法(LRU):最久沒(méi)有訪問(wèn)的內(nèi)容作為替換對(duì)象
- 非最近使用算法(NMRU):在最近沒(méi)有使用的內(nèi)容中隨機(jī)選擇一個(gè)作為替換對(duì)象
type Lru struct {
max int
l *list.List
Call func(key interface{}, value interface{})
cache map[interface{}]*list.Element
mu *sync.Mutex
}
type Node struct {
Key interface{}
Val interface{}
}
func NewLru(len int) *Lru {
return &Lru{
max: len,
l: list.New(),
cache: make(map[interface{}]*list.Element),
mu: new(sync.Mutex),
}
}
func (l *Lru) Add(key interface{}, val interface{}) error {
if l.l == nil {
return errors.New("not init NewLru")
}
l.mu.Lock()
defer l.mu.Unlock()
if e, ok := l.cache[key]; ok { //以及存在
e.Value.(*Node).Val = val
l.l.MoveToFront(e)
return nil
}
ele := l.l.PushFront(&Node{
Key: key,
Val: val,
})
l.cache[key] = ele
if l.max != 0 && l.l.Len() > l.max {
if e := l.l.Back(); e != nil {
l.l.Remove(e)
node := e.Value.(*Node)
delete(l.cache, node.Key)
if l.Call != nil {
l.Call(node.Key, node.Val)
}
}
}
return nil
}
func (l *Lru) Get(key interface{}) (val interface{}, ok bool) {
if l.cache == nil {
return
}
l.mu.Lock()
defer l.mu.Unlock()
if ele, ok := l.cache[key]; ok {
l.l.MoveToFront(ele)
return ele.Value.(*Node).Val, true
}
return
}
func (l *Lru) GetAll() []*Node {
l.mu.Lock()
defer l.mu.Unlock()
var data []*Node
for _, v := range l.cache {
data = append(data, v.Value.(*Node))
}
return data
}
func (l *Lru) Del(key interface{}) {
if l.cache == nil {
return
}
l.mu.Lock()
defer l.mu.Unlock()
if ele, ok := l.cache[key]; ok {
delete(l.cache, ele)
if e := l.l.Back(); e != nil {
l.l.Remove(e)
delete(l.cache, key)
if l.Call != nil {
node := e.Value.(*Node)
l.Call(node.Key, node.Val)
}
}
}
}