lru算法php,Golang 实现LRU算法

缓存文件置换机制是计算机处理缓存存储器的一种机制。

计算机存储器空间的大小固定,无法容纳服务器上所有的文件,所以当有新的文件要被置换入缓存时,必须根据一定的原则来取代掉适当的文件。此原则即所谓缓存文件置换机制。

缓存文件置换方法有:

先进先出算法(FIFO):最先进入的内容作为替换对象

最近最少使用算法(LFU):最近最少使用的内容作为替换对象

最久未使用算法(LRU):最久没有访问的内容作为替换对象

非最近使用算法(NMRU):在最近没有使用的内容中随机选择一个作为替换对象

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)

}

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值