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 函数的短函数的使用

  • 相关阅读:
    ADO.NET中容易混淆的概念(4)
    ADO.NET中容易混淆的概念(3)
    ADO.NET中容易混淆的概念(2)
    ADO.NET中容易混淆的概念(1)
    引用计数
    ADO.NET中SQL Server数据库连接池
    Python之禅!
    django总结
    Python第六周学习之Linux
    Python第五周前端学习之HTML5/ CSS / JS
  • 原文地址:https://www.cnblogs.com/guokefa/p/12118765.html
Copyright © 2011-2022 走看看