123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657 |
- <?php
- /**
- * Created by PhpStorm.
- * User: huangjianfeng
- * Date: 2019-01-10
- * Time: 20:41
- */
- namespace app\command\Org;
- class RedisPool
- {
- private $host;
- private $port;
- protected $available = true;
- public function __construct($host = '127.0.0.1',$port = 6379)
- {
- $this->pool = new \SplQueue;
- $this->host = $host;
- $this->port = $port;
- }
- public function put($redis)
- {
- $this->pool->push($redis);
- }
- public function get()
- {
- //有空闲连接且连接池处于可用状态
- if ($this->available && count($this->pool) > 0) {
- return $this->pool->pop();
- }
- //无空闲连接,创建新连接
- $redis = new \Swoole\Coroutine\Redis();
- // $redis->setOption(\Redis::OPT_SCAN,\Redis::SCAN_RETRY);
- $res = $redis->connect($this->host, $this->port);
- if ($res == false) {
- return false;
- } else {
- return $redis;
- }
- }
- public function destruct()
- {
- // 连接池销毁, 置不可用状态, 防止新的客户端进入常驻连接池, 导致服务器无法平滑退出
- $this->available = false;
- while (!$this->pool->isEmpty()) {
- $this->pool->pop();
- }
- }
- }
|