<?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();
        }
    }
}