swoole 协程channel乱测

channel和数组差不多,可以被用作队列,属性capacity是设置容量,isEmpty() isFull() 用来判断队列是空还是满,push()加入队列 pop()弹出队列

interface pusher
{
    function push($data);
}
#require 'redisconn.php';
class mypusher implements pusher
{
    protected $mychannel;
    protected $size=10;
    public function __construct()
    {
        $this->mychannel = new Swoole\Coroutine\Channel(10);
        $this->mylen = $this->mychannel->length();
        echo "容量".$this->mychannel->capacity.PHP_EOL;
    }

    public function push($data)
    {
        if ($this->mychannel->isFull())
        {
            return 0;
        }
        else{
            //发送通知
            $this->mychannel->push($data);
            echo "当前元素个数".$this->mychannel->length();
            return 1;
        }
    }

    public function pop()
    {
        if($this->mychannel->isEmpty())
        {
            return 0;
        }
        else
        {
            echo "当前元素个数".$this->mychannel->length().PHP_EOL;
            var_dump($this->mychannel->pop());
            echo PHP_EOL."还剩元素个数".$this->mychannel->length().PHP_EOL;
            return 1;
        }
    }
}
go(function (){
    $thispusher = new mypusher();
    $thispusher->push(['name'=>'cj','age'=>20]);
    $thispusher->push(['name'=>'cpc','age'=>22]);
    $thispusher->push(['name'=>'xxd','age'=>40]);
    $thispusher->pop();
    $thispusher->pop();
    $thispusher->pop();

});

测试结果:

容量10
当前元素个数1当前元素个数2当前元素个数3当前元素个数3
array(2) {
  ["name"]=>
  string(2) "cj"
  ["age"]=>
  int(20)
}

还剩元素个数2
当前元素个数2
array(2) {
  ["name"]=>
  string(3) "cpc"
  ["age"]=>
  int(22)
}

还剩元素个数1
当前元素个数1
array(2) {
  ["name"]=>
  string(3) "xxd"
  ["age"]=>
  int(40)
}

还剩元素个数0
  • 实现一个redis连接池
class redispool
{
    protected $mypool;
    public function __construct($size)
    {
        $this->mypool = new Swoole\Coroutine\Channel($size);
        for ($i=0;$i<$size;$i++)
        {
            $redis = new Swoole\Coroutine\Redis();
            $redis->setOptions(['compatibility_mode' => true]);
            $rconn = $redis->connect('127.0.0.1',6379);
            if ($rconn == false)
            {
                throw new \http\Exception\RuntimeException('Damn~ fail to connet redis-server');
            }
            else{
                $this->mypool->push($redis);
            }
        }
    }

    public function push($redis)
    {
        $this->mypool->push($redis);
    }
    public function pop()
    {
        return $this->mypool->pop();
    }
}

 

转载于:https://www.cnblogs.com/saintdingspage/p/11276399.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值