zoukankan      html  css  js  c++  java
  • php swoole实现简单redis连接池

    <?php declare(strict_types=1);
    
    Co
    un(function(){
        go(function(){
            redisPool::i();
            for ($c=1000;$c--;){
                $pool = RedisPool::i();
                $redis = $pool->get();
                defer(function() use($pool,$redis){
                    $pool->put($redis);
                });
                $value = $redis->get('foo');
                if($value === false){
                    throw new RuntimeException('get undefined');
                }
    
                assert($value,'bar');
            }
        });
    });
    
    
    
    class RedisPool
    {
        protected $channel;
        protected static $instance;
    
        public static function i() : self
        {
            return !empty(static::$instance) ? static::$instance : (static::$instance = new static());
        }
    
        public function __construct(int $size=100)
        {
            $this->channel = new SwooleCoroutineChannel($size);
            while ($size --)
            {
                $redis = new SwooleCoroutineRedis();
                $res = $redis->connect('127.0.0.1',6379);
                if($res === true){
                    $this->put($redis);
                }else{
                    throw new RuntimeException('cannot connect redis');
                }
            }
        }
    
        public function put(SwooleCoroutineRedis $redis) : void
        {
            $this->channel->push($redis);
        }
    
        public function get(float $timeout = -1) : ?SwooleCoroutineRedis
        {
            return $this->channel->pop($timeout) ? : null;
        }
    
        public function close()
        {
            return $this->channel->close();
        }
    }

    注意点:

    /etc/php.ini  配置 swoole.use_shortname = On  开启swoole go 函数的短函数的使用

  • 相关阅读:
    GTD时间管理(1)---捕获搜集
    ios面试总结-
    Swift入门篇-结构体
    Swift入门篇-闭包和函数
    swift入门篇-函数
    Swift入门篇-集合
    Swift入门篇-循环语句
    Swift入门篇-基本类型(3)
    Swift入门篇-基本类型(2)
    Swift入门篇-基本类型(1)
  • 原文地址:https://www.cnblogs.com/guokefa/p/12118765.html
Copyright © 2011-2022 走看看