不言不语

您现在的位置是: 首页 >  PHP

PHP

PHP遍历Memcache数据

2022-06-05PHP
Memcache的客户端操作一般都只提供了get,set,stats等简单的操作,但是在某些特殊时候,我们可能需要遍历Memcache的数据,Memcache自带的命令是不能实现的,我们需要通过程序来实现。下面带大家一起看看PHP是如何遍历Memcache数据的。

PHP遍历Memcache数据实现的思路

1、stats items命令,查看所有的item.

1
2
3
4
5
6
7
8

[root@memcache ~]# telnet localhost 11211
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
stats items
STAT items:1:number 2
STAT items:1:age 190
END

2、循环遍历stats cachedump 1 0命令。这里的1表示上面图中items后面的数字。0表示显示全部的数据,1表示显示1条。查看item后面的字符串为key.

1
2
3
4

stats cachedump 1 0
ITEM key [10 b; 1446601997 s]
ITEM name [8 b; 1446601966 s]
END

3、循环遍历所有的key获取value值。

1
2
3
4

get key
VALUE key 32 10
leixuesong
END

PHP实循环遍历Memcache数据的代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

$host='localhost';
$port=11211;
$mem=new Memcache();
$mem->connect($host,$port);
$items=$mem->getExtendedStats ('items');
$items=$items["$host:$port"]['items'];
foreach($items as $key=>$values){
$number=$key;;
$str=$mem->getExtendedStats ("cachedump",$number,0);
$line=$str["$host:$port"];
if( is_array($line) && count($line)>0){
foreach($line as $key=>$value){
echo $key.'=>';
print_r($mem->get($key));
echo "\r\n";
}
}
}


文章评论