PHP Predis:如何获取/删除包含特殊字符的密钥


PHP Predis: how to get/delete keys containing special characters?

我需要删除一个包含一些特殊密钥的密钥(在我的情况下是方括号):

我做了以下操作,但它不起作用:

$this->redis;    
$keys = $this->redis->keys("*");
foreach ($keys as $key) {
    // keys are in the following format:   
    //    vir3_data_cache[zones_cdc_shifting_series_2013_5][1]
    $this->redis->del($key);
    // no key was deleted
}

我也试图引用关键,但没有成功:

$this->redis;    
$keys = $this->redis->keys("*");
foreach ($keys as $key) {
    // keys are in the following format:   
    //    vir3_data_cache[zones_cdc_shifting_series_2013_5][1]
    $quotedKey = addslashes(addslashes($key));
    $this->redis->del($quotedKey);
    // no key was deleted
}

已解决。这个问题与predis在执行任何操作之前在每个键的开头(在我的例子中是"vir3_data_cache")自动插入一个配置的前缀有关。但是keys("*")命令并没有从密钥中去掉前缀。

因此,为了使我的代码正常工作,我需要做以下操作:

$prefix = $this->redis->getOptions()->__get('prefix')->getPrefix();
$keys = $this->redis->keys("*");
$removed = 0;
foreach ($keys as $key) {
    if (substr($key, 0, strlen($prefix)) == $prefix) {
        $key = substr($key, strlen($prefix));
    }              
}

使用phpredis时,可以通过这种方式获取前缀并删除密钥模式:

<?php
...
$prefix = $redisClient->getOption(Redis::OPT_PREFIX);
$redisClient->delete(array_map(
    function ($key) use ($prefix) {
        return str_replace($prefix, '', $key);
    }, $redisClient->keys('*'))
);