利用composer安装redis协程客户端
可直接安装redis-pool组件实现连接池:
composer require easyswoole/redis-pool
安装 easyswoole/pool 组件自定义实现:
composer require easyswoole/pool
安装完以后在
新增文件/App/Pool/RedisPool.php
<?php
/**
* Created by PhpStorm.
* User: Tioncico
* Date: 2019/10/15 0015
* Time: 14:46
*/
namespace App\Pool;
use EasySwoole\Pool\Config;
use EasySwoole\Pool\AbstractPool;
use EasySwoole\Redis\Config\RedisConfig;
use EasySwoole\Redis\Redis;
class RedisPool extends AbstractPool
{
protected $redisConfig;
/**
* 重写构造函数,为了传入redis配置
* RedisPool constructor.
* @param Config $conf
* @param RedisConfig $redisConfig
* @throws \EasySwoole\Pool\Exception\Exception
*/
public function __construct(Config $conf,RedisConfig $redisConfig)
{
parent::__construct($conf);
$this->redisConfig = $redisConfig;
}
protected function createObject()
{
//根据传入的redis配置进行new 一个redis
$redis = new Redis($this->redisConfig);
return $redis;
}
}
在dev.php中配置redis连接配置
配置代码
$config = new \EasySwoole\Pool\Config();
$redisConfig1 = new \EasySwoole\Redis\Config\RedisConfig(\EasySwoole\EasySwoole\Config::getInstance()->getConf('REDIS'));
\EasySwoole\Pool\Manager::getInstance()->register(new \App\Pool\RedisPool($config,$redisConfig1),'redis');
使用示例:
<?php
namespace App\HttpController\Learn;
use EasySwoole\Http\AbstractInterface\Controller;
/**
* Created by PhpStorm.
* User: zq2020
* Date: 20-2-27
* Time: 下午3:2
* */
class Redis extends Controller{
public function index()
{
$redis=\EasySwoole\Pool\Manager::getInstance()->get('redis')->getObj();
if(!$res=$redis->get("name")){
$redis->set("name","zq");
$redis->expire("name",400);
}
$res=$redis->get("name");
\EasySwoole\Pool\Manager::getInstance()->get('redis')->recycleObj($redis);
return $this->writeJson(200,$res);
}
public function push(){
$redis=\EasySwoole\Pool\Manager::getInstance()->get('redis')->getObj();
$redis->lpush("list",time());
\EasySwoole\Pool\Manager::getInstance()->get('redis')->recycleObj($redis);
return $this->writeJson(0,"push list success");
}
public function pop(){
$redis=\EasySwoole\Pool\Manager::getInstance()->get('redis')->getObj();
$result=$redis->rpop("list");
\EasySwoole\Pool\Manager::getInstance()->get('redis')->recycleObj($redis);
return $this->writeJson(0,$result);
}
}