PHP有不少Redis库,比如pecl的Redis库(phpredis),就是直接自带了数组的存取和读出,因为他在存储和读出的时候自动序列化了。象是象predis就不行,如果你直接存一个数组去,那么它就会报warning,同时存一个Array到指定的KEY上。

但是predis允许你封装自定义的redis方法。比如jsonset/jsonget,这时候你利用这些自定义的方法来获取或写入数组即可。(基于Laravel,其他的也一样,其他参考:Setting arrays · Issue #136 · predis/predis (github.com))

只是官方的Issue中 【Predis\Profile\ServerProfile:】已经不存在了,要换成【Predis\Profile\Factory】,其余可以复制

----

基于Laravel的话,上述的数组可以放到config里,就啥出不用配置了~~

if (!function_exists('yredis')) {
class StringSetJson extends Predis\Command\StringSet
{
protected function filterArguments(array $arguments)
{
$arguments[1] = json_encode($arguments[1]);
return $arguments;
}
}

class StringGetJson extends Predis\Command\StringGet
{
public function parseResponse($data)
{
return json_decode($data, true);
}
}

class StringSetPhp extends Predis\Command\StringSet
{
protected function filterArguments(array $arguments)
{
$arguments[1] = serialize($arguments[1]);
return $arguments;
}
}

class StringGetPhp extends Predis\Command\StringGet
{
public function parseResponse($data)
{
return unserialize($data);
}
}

/**
* 这个方法是为了读redis,但是不含prefix
* @param string $connection
* @return RedisManager
*/
function yredis()
{
try {
$redis = app('yredis');
} catch (Exception $e) {
app()->singleton('yredis', function ($app) {
$config = $app->make('config')->get('database.redis', []);
unset($config['options']['prefix']);
if(env('REDIS_CLIENT') == 'predis'){
$config['options']['profile'] = function ($options, $option) {
$profile = \Predis\Profile\Factory::getDefault();
$profile->defineCommand('jsonset', 'StringSetJson');
$profile->defineCommand('jsonget', 'StringGetJson');
$profile->defineCommand('phpset', 'StringSetPhp');
$profile->defineCommand('phpget', 'StringGetPhp');
return $profile;
};
}
return new \Illuminate\Redis\RedisManager($app, \Illuminate\Support\Arr::pull($config, 'client', 'phpredis'), $config);
});
app()->bind('yredis.connection', function ($app) {
return $app['yredis']->connection();
});
$redis = app('yredis');
}
return $redis;
}
}
因为laravel的默认config会带 prefix,所以写一个简单的,其实就是为了在写数据的时候不加 prefix 。。。