首先在配置文件中配置Reids
//Redis 配置
'DATA_CACHE_PREFIX' => 'Redis_', //缓存前缀
'DATA_CACHE_TYPE'=>'Redis', //默认动态缓存为Redis
'REDIS_RW_SEPARATE' => true, //Redis读写分离 true 开启
'REDIS_HOST'=>'127.0.0.1', //redis服务器ip,多台用逗号隔开;读写分离开启时,第一台负责写,其它[随机]负责读;
'REDIS_PORT'=>'6379', //端口号
'REDIS_TIMEOUT'=>'300', //超时时间
'REDIS_EXPIRE'=>'1800', //失效时间
'REDIS_PERSISTENT'=>false, //是否长连接 false=短连接
'REDIS_AUTH'=>'', //AUTH认证密码(如果你在服务器的Redis配置中配置了密码就写上,没有就默认为空)
然后在控制器中测试测试
namespace Api\Controller;
/**
* Redis缓存及队列测试
*/
class TestController extends ApiController {
private $Redis;
private $Expire;
public function __construct()
{
parent::__construct();
$this -> Redis = new \Redis();
$this -> Redis -> connect(C('REDIS_HOST'),C('REDIS_PORT'));
$this -> Expire = C('REDIS_EXPIRE');
}
public function index(){
//测试使用的数据
$list = [
'name'=>'张三',
'sex'=>'男',
'age'=>'18'
];
//判断Redis缓存存不存在,在就获取缓存,不在就缓存
if($this -> Redis ->exists('list_cs')){
echo '<pre/>';
print_r(json_decode($this -> Redis ->get('list_cs')));
}else{
if($list){
$this -> Redis ->set('list_cs',json_encode($list));
$this -> Redis ->expire('list_cs',$this -> Expire);
}else{
echo '获取数据失败';
}
}
//测试打印数据如下(然后注释测试使用的数据看看是否还能获取如下数据,如果能获取说明你的Redis缓存成功)
stdClass Object (
[name] => 张三
[sex] => 男
[age] => 18
)
//队列
$msg = 'Messages';
$this->Redis->rpush($msg,json_encode(['uid'=>1,'name'=>'111123']));
$this->Redis->rpush($msg,json_encode(['uid'=>2,'name'=>'2222']));
$this->Redis->rpush($msg,json_encode(['uid'=>3,'name'=>'3333']));
//$this->Redis->rpush($msg,json_encode(['uid'=>4,'name'=>'4444']));
$count = $this->Redis->lrange($msg,0,-1);
echo '<pre/>';
echo"当前队列数据为:";
print_r($count);
$this->Redis->lpop($msg);
echo '出列成功';
$count = $this->Redis->lrange($msg,0,-1);
echo '<pre/>';
echo"当前队列数据为:";
print_r($count);
//$this->Redis->delete($msg);
}
}