Redis针对不同的数据类型有许多不同的操作函数,我们用单例模式的思想实现Redis 所有函数的封装。
class Db_Redis { private static $redis; static function instance($cfg='') { if(self::$redis instanceof Redis ) { return self::$redis; } else { //读取连接配置 $config = Config('I Am config '); self::$redis = new Redis(); $re = self::$redis->connect($config['host'],$config['port']); if( !$re ) throw new Exception("Connect Redis Really Failed"); //配置密码 if( $config['auth'] ) self::$redis->auth($config['auth']); return self::$redis; } } /** * 魔术方法,实现所有REDIS自有方法 * * @param string $method * @param array $args * @return mixed */ static function __callstatic($method, $args){ # 初始化数据 $cmd = $result = array(); # 如果方法名包含 _json 后缀,则返回 json 格式 if($pos = strpos($method, '_json')){ $method = substr($method, 0, $pos); } # 处理参数 foreach ($args as $arg) { is_array($arg) && ($arg = json_encode($arg)); $cmd[] = $arg == 'null'? $arg: "'$arg'"; } # 执行REDIS查询 eval('$result = Db_Redis::instance()->'.$method.'('.join(',', $cmd).');'); # 返回JSON格式 if($pos) return json_decode($result, true); # 返回字符串格式 return $result; } }
比如队列机的使用:
$result = array('key'=>'value'); DB_Redis::lpush('sys',$result); $re = DB_Redis::rpop_json('sys); $re 为之前push入队列的result