在extend/my添加一个类,extend 是thinkPHP5.0的,可手动创建扩展类
控制器参考 因为我们从数据库内获取的数据是一个对象,所以我们在封装类中需要对数据序列化
public function Move(){
try {
$model=new Books();
$redis=new RedisPackage();
$res=$model->select();
// 存入缓存
$redis::set('res',$res);
// 从缓存内获取
$move=$redis::get('res');
}catch (Exception $exception){
return json(['code'=>1,'data'=>'','msg'=>'查询异常']);
}
if(empty($move)){
return json(['code'=>1,'data'=>$move,'msg'=>'查询失败']);
}else{
return json(['code'=>0,'data'=>$move,'msg'=>'查询成功']);
}
}
创建位置
参考:
'127.0.0.1',
'port' => 6379,
'password' => '',
'select' => 0,
'timeout' => 0,
'expire' => 0,
'persistent' => false,
'prefix' => '',
];
public function __construct($options = [])
{
if (!extension_loaded('redis')) { //判断是否有扩展(如果你的apache没reids扩展就会抛出这个异常)
throw new BadFunctionCallException('not support: redis');
}
if (!empty($options)) {
$this->options = array_merge($this->options, $options);
}
$func = $this->options['persistent'] ? 'pconnect' : 'connect'; //判断是否长连接
self::$handler = new Redis;
self::$handler->$func($this->options['host'], $this->options['port'], $this->options['timeout']);
if ('' != $this->options['password']) {
self::$handler->auth($this->options['password']);
}
if (0 != $this->options['select']) {
self::$handler->select($this->options['select']);
}
}
public static function set($key,$value){
判断存入数据是否是一个对象
if(is_object($value)||is_array($value)){
将数据序列化
$value = serialize($value);
}
return self::$handler-> set($key,$value);
}
public static function get($key){
$value = self::$handler-> get($key);
反序列化数据在输出
$value_serl = @unserialize($value);
return $value_serl;
}
}



