当前位置

Memcached中文Key的问题

James Qi 在 2021年6月28日 - 16:43 提交

今天同事需要清理memcache中某种前缀的key的值,但memcache没有专门的这种命令,我帮忙在网上找了一段程序

How about this function in php:

function deletekeysbyindex($prefix) {
    $m = new Memcached();
    $m->addServer('localhost', 11211);
    $keys = $m->getAllKeys();
    foreach ($keys as $index => $key) {
        if (strpos($key,$prefix) !== 0) {
            unset($keys[$index]);
        } else {
            $m->delete($key);
        }
    }
    return $keys;
}
Deletes keys beginning with $prefix and returns a list of all keys removed. I ran this on 30,000+ keys just now on a shared server and it was pretty quick - probably less than one second.

同事采用了这种办法,可以列出、删除某种前缀的key的键值对,不过打印的时候,key中包含的中文没有显示,不确定是否正确。

我在网上去搜了一些资料,中文的资料比较少而且说法不一,多数说需要对中文进行编码再做key,英文资料多一些,也有些说法不一,可能是memcache新老版本的问题,最后看到memcache只有这几种不能作为key:Keys cannot have spaces, new lines, carriage returns, or null characters. 其它的应该都可以。

https://github.com/pinterest/pymemcache/issues/122
这里说:
memcached supports unicode for both keys and values. Example run against a local memcached.

So we don't need to do any hashing for unicode keys.

$ echo -e 'add my☃ 0 60 11\r\nhello ☃ld\r' | nc localhost 11211
STORED
$ echo -e 'get my☃\r' | nc localhost 11211
VALUE my☃ 0 11
hello ☃ld
END

我自己检查了以前在一个drupal网站中使用emoji做key的一部分的情况,memcached是可以自动进行urlencode编码的:

最后同事直接在PHP程序中逐段调试,也证明可以直接用中文作为key的一部分,add和get都是OK的。👌

这也说明一个问题,网上资料不一定靠谱,最终还是要自己实践来证实!

自由标签:

添加新评论

Plain text

  • 不允许使用HTML标签。
  • 自动将网址与电子邮件地址转变为链接。
  • 自动断行和分段。