Skip to main content

Redis如何保存数组和对象

个人建议使用PHP自带的序列化函数serialize和unserialize函数

我们可以封装一个自己的Redis类

<?php
class MyRedis{
private static $handler;

private static function handler(){
if(!self::$handler){
self::$handler = new Redis();
self::$handler -> connect('127.0.0.1','6379');
}
return self::$handler;
}

public static function get($key){
$value = self::handler() -> get($key);
$value_serl = @unserialize($value);
if(is_object($value_serl)||is_array($value_serl)){
return $value_serl;
}
return $value;
}

public static function set($key,$value){
if(is_object($value)||is_array($value)){
$value = serialize($value);
}

return self::handler() -> set($key,$value);
}

}

调用测试

<?php
require_once 'MyRedis.php';

class MyObj{
public function rTime(){
return time();
}
}

$arr = array(1,2,3);
$obj = new MyObj();
$str = ' My name is Jeffrey.';

MyRedis::set('arr',$arr);
MyRedis::set('obj',$obj);
MyRedis::set('str',$str);

$_arr = MyRedis::get('arr');
$_obj = MyRedis::get('obj');
$_str = MyRedis::get('str');

var_dump($_arr);
var_dump($_obj->rTime());
var_dump($_str);