基于swoole的简易连接池

通过swoole的chan实现简易的连接池基类,有需要的小伙伴可以参考一下。

<?php
abstract class Pool
{
    /**
     * 客户端使用管道存储
     * @var \chan
     */
    private $clients;
    /**
     * 最大值
     * @var int
     */
    protected $size = 200;
    /**
     * 缺省值
     * @var int
     */
    protected $defaultSize = 10;
    /**
     * 超时时间
     * @var int
     */
    protected $timeout = 3;
    /**
     * 检测时间
     * @var float|int
     */
    protected $intervalMs = 15 * 1000;
    /**
     * 是否开启自动检测
     * @var bool
     */
    protected $autoCheck = false;

    protected function __construct()
    {
        $this->clients = new \chan($this->size);

        // 自动检测
        if($this->autoCheck){
            swoole_timer_tick($this->intervalMs,function (){
                while ($this->clients->length() > $this->defaultSize){
                    $client = $this->clients->pop($this->timeout);
                    $this->disconnect($client);
                }
            });
        }
    }

    /**
     * 获取客户端
     * @return mixed
     */
    final public function get()
    {
        $client = $this->clients->pop($this->timeout);
        if (empty($client)) {
            $client = $this->getClient();
        }

        if ($this->check($client) == false) {
            $client = $this->getClient();
        }

        defer(function () use ($client) {
            $this->push($client);
        });

        return $client;
    }

    /**
     * 入栈
     * @param $client
     * @return bool
     */
    final protected function push($client)
    {
        if ($this->clients->isFull()) {
            $this->disconnect($client);
            return false;
        }
        $this->clients->push($client);
        return true;
    }

    /**
     * 获取客户端
     * @return mixed
     */
    final protected function getClient()
    {
        $client = $this->connect();
        $this->push($client);
        return $client;
    }

    abstract protected function check($client): bool;

    abstract protected function disconnect($client);

    abstract protected function connect();
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值