PHP-如何遍历Memcached中的所有键值

PHP-如何遍历Memcached中的所有键值

清晨说ぺ晚安 发布于 2017-01-09 字数 116 浏览 1056 回复 2

如何遍历Memcached中的所有键值,telnet localhost memcached端口,只能get一个key,不能遍历所有key,有好的办法么?

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

泛泛之交 2017-11-03 2 楼

之前查询项目中超出一定大小的memcache值时,是用php的扩展查的,下边是代码,把判断大于阈值的控制语句去掉,应该就是遍历所有的key了:

<?php
/***** CONFIG *****/
$host = 'localhost';
$port = 12321;
$sizeLimit = 5000;
/******************/

$mem = new Memcache();
$mem->connect($host, $port);
$items = $mem->getExtendedStats('items');
$items = $items["$host:$port"]['items'];
// $items2 = $mem->getExtendedStats('stats detail dump');
if (!empty($items)) foreach ($items as $item) {
$number = $item['number'];
$str = $mem->getExtendedStats("cachedump", $number, 0);
$line = $str["$host:$port"];
foreach ($line as $key => $value) {
$v = $mem->get($key);
if (is_string($v)) {
$size = strlen($v);
} else {
$size = strlen(serialize($v));
}
if ($size >= $sizeLimit) {
echo "size:{$size},key:{$key}n";
}
}
}

?>

泛泛之交 2017-01-24 1 楼

我也分享一个:

#!/usr/bin/env ruby
require 'socket'

#1. stats
#2. stats reset
#3. stats malloc
#4. stats maps
#5. stats sizes
#6. stats slabs
#7. stats items
#8. stats cachedump slab_id limit_num
#9. stats detail [on|off|dump]

class Memcache
class << self
def open(host, port)
s = TCPSocket.open(host, port)
yield s if block_given?
ensure
s.close if s
end

def command(command_string, s)
s.send(command_string + "rn", 0)
buff = []
until ["END", "OK", "DELETE", "ERROR"].include?(line = s.gets.strip) do
buff << line
end
buff
end

def exec(command_string, host = "127.0.0.1", port = 12321)
open(host, port) { |socket| command(command_string, socket).each {|line| puts line } }
end

def cache_stats(host = "127.0.0.1", port = 12321)
cache_objects = {}
open(host, port) do |socket|
slabs = []
command("stats items", socket).each do |line|
slab_id = line.split[1].split(":")[1].to_i
slabs << slab_id unless slabs.include?(slab_id)
end
slabs.each do |slab_id|
puts "browse slab #{slab_id}..."
command("stats cachedump #{slab_id} 0", socket).each do |item|
key = item.split[1].split("/")[0].to_s
cache_objects.include?(key) ? cache_objects[key] += 1 : cache_objects[key] = 1
end
end
end
cache_objects.each_pair {|key, value| puts "#{key} : #{value}"}
end
end
end

if ARGV.size == 0
Memcache.cache_stats
else
Memcache.exec(ARGV.join(" "))
end

以下为命令模式
telnet localhost 12321

执行stats items命令,可以看到出现 很多的items行

stats items

STAT items:1:number 40
STAT items:1:age 1475528
STAT items:1:evicted 0
STAT items:1:evicted_nonzero 0
STAT items:1:evicted_time 0
STAT items:1:outofmemory 0
STAT items:1:tailrepairs 0
STAT items:1:reclaimed 77
STAT items:5:number 1
STAT items:5:age 1978249
STAT items:5:evicted 0
STAT items:5:evicted_nonzero 0
STAT items:5:evicted_time 0
STAT items:5:outofmemory 0
STAT items:5:tailrepairs 0
STAT items:5:reclaimed 22

执行:stats cachedump 5 0

ITEM 31612050|346001 [7 b; 1317462258 s]
ITEM 31612114|346001 [6 b; 1317458169 s]
……………………

这里的5表示上面图中items后面的数字,0标示显示全部的数据,如果是1就标示只显示1条。