获取同步
@return \Redis
@throws SwooleException
507694
public function getSync()
    {
        if ($this->redis_client != null) {
            return $this->redis_client;
        }
        //同步redis连接，给task使用
        $this->redis_client = new \Redis();
        if ($this->redis_client->connect($this->config['redis'][$this->active]['ip'], $this->config['redis'][$this->active]['port']) == false) {
            throw new SwooleException($this->redis_client->getLastError());
            $this->redis_client = null;
        }
        if (!empty($this->config->get('redis.' . $this->active . '.password', ""))) {//存在验证
            if ($this->redis_client->auth($this->config['redis'][$this->active]['password']) == false) {
                throw new SwooleException($this->redis_client->getLastError());
                $this->redis_client = null;
            }
        }
        if ($this->config->has('redis.' . $this->active . '.select')) {//存在select
            $this->redis_client->select($this->config['redis'][$this->active]['select']);
        }
        return $this->redis_client;
    }
770365
public function getMethod()
    {
        if (isset($this->swooleRequest->post[$this->methodParam])) {
            return strtoupper($this->swooleRequest->post[$this->methodParam]);
        }

        if (isset($this->swooleRequest->server['HTTP_X_HTTP_METHOD_OVERRIDE'])) {
            return strtoupper($this->swooleRequest->server['HTTP_X_HTTP_METHOD_OVERRIDE']);
        }

        if (isset($this->swooleRequest->server['REQUEST_METHOD'])) {
            return strtoupper($this->swooleRequest->server['REQUEST_METHOD']);
        }

        return 'GET';
    }
353955
public static function redis() {
        $redisCache = self::getCache();
        if ($redisCache instanceof RedisCache) {
            $redisCache->open();
            return $redisCache->redis;
        }
        return null;
    }
159640
protected function bindSwooleEvents(SwServer $swoole, string $protocolName): SwServer
    {
        // {{ 初始化 Swoole Server 事件
        $events = [
            'Start'         => 'onMasterStart',
            'Shutdown'      => 'onMasterStop',
            'ManagerStart'  => 'onManagerStart',
            'WorkerStart'   => 'onWorkerStart',
            'WorkerStop'    => 'onWorkerStop',
            'WorkerError'   => 'onWorkerError',
            'WorkerExit'    => 'onWorkerExit',
            'PipeMessage'   => 'onPipeMessage',
            'Connect'       => 'onConnect',
            'Close'         => 'onClose',
            'Receive'       => 'onReceive',
        ];

        array_walk($events, function ($handler, $event) use ($swoole) {
            $swoole->on($event, [$this, $handler]);
        });

        unset($events);

        switch ($protocolName) {
            // HTTP Server
            case Protocol::HTTP:
                $swoole->on('Request', [$this, 'onRequest']);
                break;

            // UDP Server
            case Protocol::UDP:
                $swoole->on('Packet', [$this, 'onPacket']);
                break;

            // WebSocket Server
            case Protocol::WEBSOCKET:
                $swoole->on('Open', [$this, 'onOpen']);
                $swoole->on('HandShake', [$this, 'onHandShake']);
                $swoole->on('Message', [$this, 'onMessage']);
                break;
        }

        $tasks = isset($swoole->setting['task_worker_num']) ?
                (int) $swoole->setting['task_worker_num'] :
                0;

        if ($tasks > 0) {
            $swoole->on('Task', [$this, 'onTask']);
            $swoole->on('Finish', [$this, 'onFinish']);
        }

        unset($tasks);
        // }}

        return $swoole;
    }
181132
protected function __tryLock()
    {
        return PoolManager::use($this->poolName, function($resource, $redis){
            return 1 == $redis->evalEx(<<<SCRIPT
local key     = KEYS[1]
local content = KEYS[2]
local ttl     = ARGV[2]
local db      = ARGV[1]
redis.call('select', db)
local lockSet = redis.call('setnx', key, content)
if lockSet == 1 then
redis.call('pexpire', key, ttl)
else 
local value = redis.call('get', key)
if(value == content) then
lockSet = 1;
redis.call('pexpire', key, ttl)
end
end
return lockSet
SCRIPT
            , [
                $this->key,
                $this->guid,
                $this->db,
                $this->lockExpire,
            ], 2);
        });
    }
381856
private function useRedis($callback)
    {
        return PoolManager::use($this->redisPool, function($resource, $redis) use($callback){
            $redis->select($this->redisDb);
            return $callback($resource, $redis);
        });
    }
892633
public function http()
    {
        $this->writeln('Starting swoole http server...');

        $server = new HttpServer(
            $this->swooleConfig['http']['host'] ?? self::DEFAULT_SWOOLE_HOST,
            $this->swooleConfig['http']['port'] ?? self::DEFAULT_SWOOLE_PORT
        );

        $server->on(
            'Request', function ($request, $response) {

                $swooleRequest = (new SwooleRequest())->setSwooleRequest($request);
                $swooleResponse = (new SwooleResponse())->setSwooleResponse($response);
                $sessionId = $swooleRequest->getCookie('swoole_session_id');
                if (!$sessionId) {
                    $sessionId = IdGenerator::component()->generate();
                    $swooleResponse->setCookie('swoole_session_id', $sessionId);
                }
                $swooleRequest->setSessionId($sessionId);
                $swooleResponse->setSessionId($sessionId);

                (new App($swooleRequest, $swooleResponse))->run();

            }
        );

        $server->start();
    }
456699
public function get()
    {
        do {
            $response = $this->redis->rpop("job_queue");
            usleep(500);
        } while ($response === null);
        return unserialize($response);
    }
518463
public function udp()
    {
        $this->writeln('Starting swoole udp server...');

        $udpServer = new TcpServer(
            $this->swooleConfig['upd']['host'] ?? self::DEFAULT_SWOOLE_HOST,
            $this->swooleConfig['upd']['port'] ?? self::DEFAULT_SWOOLE_PORT,
            SWOOLE_PROCESS,
            SWOOLE_SOCK_UDP
        );

        //防止粘包
        $udpServer->set(
            [
            'open_eof_split' => true,
            'package_eof' => self::EOF,
            ]
        );

        $udpServer->on(
            'Packet', function ($serv, $data, $clientInfo) {
                $clientAddress = $clientInfo['address'];
                $clientPort = $clientInfo['port'];
                $jsonData = JsonHelper::decode(str_replace(self::EOF, '', $data));
                if (isset($jsonData['handler'])) {
                    $jsonData['swoole_client_info'] = $clientInfo;
                    $handlerClass = $jsonData['handler'];
                    try {
                        $serv->sendto(
                            $clientAddress,
                            $clientPort,
                            Lb::app()->dispatchJob($handlerClass, $jsonData)
                        );
                    } catch (\Throwable $e) {
                        $serv->sendto(
                            $clientAddress,
                            $clientPort,
                            'Exception:' . $e->getTraceAsString()
                        );
                    }
                } else {
                    $serv->sendto(
                        $clientAddress,
                        $clientPort,
                        'Handler not exists'
                    );
                }
            }
        );

        $udpServer->start();
    }
777904
public function udpClient()
    {
        $this->writeln('Starting demo swoole udp client...');

        $client = new TcpClient(SWOOLE_SOCK_UDP, SWOOLE_SOCK_ASYNC);

        $client->on(
            'connect', function ($cli) {
                //发送数据中不能包含'\r\n\r\n'
                $cli->send(JsonHelper::encode(['handler' => SwooleTcpJob::class]) . self::EOF);
            }
        );
        $client->on(
            'receive', function ($cli, $data) {
                $this->writeln('Received: '.$data);
            }
        );
        $client->on(
            'error', function ($cli) {
                $this->writeln('Connect failed');
            }
        );
        $client->on(
            "close", function ($cli) {
                $this->writeln('Connection close');
            }
        );

        $client->connect(
            $this->swooleConfig['udp']['host'] ?? self::DEFAULT_SWOOLE_HOST,
            $this->swooleConfig['udp']['port'] ?? self::DEFAULT_SWOOLE_PORT,
            $this->swooleConfig['udp']['timeout'] ?? self::DEFAULT_SWOOLE_TIMEOUT
        );
    }
969794
protected function createRedisDriver()
    {
        $serverArray    = $this->config['servers'];
        $persistent     = boolval($this->config['persistent']);
        $prefix         = trim($this->config['prefix']);
        $expireTime     = intval($this->config['lifetime']);

        if ($persistent) {
            foreach ($serverArray as $k => $v) {
                $v['persistent']    = true;
                $serverArray[$k]    = $v;
            }
        }

        $redisServer    = new RedisServer($serverArray);
        $redisStore     = new RedisStore($redisServer, $prefix);
        return new CacheSessionHandler($redisStore, $expireTime);
    }
902652
public function get($key)
    {
        try {
            return $this->redis->get($key);
        } catch (\RedisException $e) {
            die("Error!: " . $e->getMessage() . "<br/>");
        }
    }
81681
private function getRaw()
    {
        if ($this->pool === null) {
            $this->pool = new ConnectionPool($this->keyspace, $this->servers);
        }
        return $this->pool->get();
    }
1255536
public function connect(): \redis
    {
        //如果已经连接,返回连接句柄
        if ($this->handle) {
            return $this->handle;
        }

        // 记录开始时间
        $start = timeLog();

        // 取此集合的配置
        $config = $config = configDefault('', 'redis');
        if (!$config) {
            trigger_error('无法读取Redis配置文件(redis)', E_USER_ERROR);
        }

        //尝试连接,出错就抛异常吧
        $this->handle = new \redis();
        $success = $this->handle->connect($config['hostname'], $config['port']);
        if (!$success) {
            trigger_error('无法连接Redis服务器(' . $config['hostname'] . ':' . $config['port'] . ')', E_USER_ERROR);
        }

        //如果设置了密码,要通过AUTH
        if (isset($config['password']) and $config['password']) {
            //如果密码不正确,提示
            if (!$this->auth($config['password'])) {
                trigger_error('Redis服务器身份验证失败', E_USER_ERROR);
            }
        }

        // 记录调试信息
        debug("connect to redis {$config['hostname']} ,persist:" . timeLog($start) * 1000 . 'ms');
        return $this->handle;
    }
306720
public function getRedisPool(string $poolName)
    {
        $activePoolName = $poolName;
        $poolName       = RedisAsynPool::ASYN_NAME . $poolName;
        if (isset($this->redisPools[$poolName])) {
            return $this->redisPools[$poolName];
        }

        $pool = getInstance()->getAsynPool($poolName);
        if (!$pool) {
            $pool = new RedisAsynPool($this->getConfig(), $activePoolName);
            getInstance()->addAsynPool($poolName, $pool, true);
        }

        $this->redisPools[$poolName] = AOPFactory::getRedisPoolCoroutine($pool->getCoroutine(), $this);
        return $this->redisPools[$poolName];
    }
27529
public function getResource()
    {
        if($this->getFree() <= 0)
        {
            if($this->getCount() < $this->config->getMaxResources())
            {
                // 没有空闲连接，当前连接数少于最大连接数
                $this->addResource();
            }
            else 
            {
                return null;
            }
        }
        $resource = $this->queue->pop();
        if(!$resource || (!$resource->checkState() && !$resource->open()))
        {
            throw new \RuntimeException(sprintf('SyncPool [%s] getResource failed', $this->getName()));
        }
        return $resource;
    }
641810
public function get()
    {
        if (!$this->isTracking()) {
            return false;
        }

        $statusPacket = json_decode($this->resqueInstance->redis->get((string)$this), true);
        if (!$statusPacket) {
            return false;
        }

        return $statusPacket['status'];
    }