-
概念 LRU : 最近最少使用算法 -
代码
<?php
class Node
{
public $preKey = null;
public $nextKey = null;
public $key= null;
public $value= null;
public function __construct($key,$value){
$this->key = $key;
$this->value = $value;
}
public function setPre($preKey)
{
$this->preKey = $preKey;
}
public function setNext($nextKey)
{
$this->nextKey = $nextKey;
}
}
class LRUCache{
public $cacheTable = [];
private $headNode = null;
private $lastNode = null;
private $cacheCount = 0;
private $cacheMax = 3;
public function addNode($key,$value)
{
$addNode = new Node($key,$value);
if ( !empty($this->headNode))
{
$this->headNode->preKey = $addNode;
}
$addNode->nextKey = $this->headNode;
if ($this->lastNode == null){
$this->lastNode = $addNode;
}
$this->headNode = $addNode;
$this->cacheTable[$key] = $addNode;
$this->cacheCount++;
}
public function set($key,$value)
{
$this->shiftNode();
$this->addNode($key,$value);
return true;
}
public function shiftNode()
{
while ($this->cacheCount >= $this->cacheMax){
if (!empty($this->lastNode)){
if ($this->lastNode->preKey){
$this->lastNode->preKey->nextKey = null;
$this->lastNode = $this->lastNode->preKey;
}
unset($this->cacheTable[$this->lastNode->key]);
}
$this->cacheCount --;
}
}
public function dumpAllData()
{
$node = $this->headNode;
while (($node)){
echo "key=".$node->key."value=".$node->value."\n";
$node = $node->nextKey;
}
}
}
$Cache = new LRUCache();
$Cache->set("a","aaaaaaaaaaa");
$Cache->set("b","bbbbbbbbbbb");
$Cache->set("c","ccccccccccc");
$Cache->set("d","dddddddddddd");
$Cache->set("e","eeeeeeeeeeee");
$Cache->dumpAllData();
- 结果
[root@VM-16-13-centos ~]
key=evalue=eeeeeeeeeeee
key=dvalue=dddddddddddd
key=cvalue=ccccccccccc
|