接口请求，超时时ret为404
@param string $service MQ中的接口服务名称，如：Default.Index
@param array $params 参数
@param int $timeoutMS 接口超时（单位：毫秒）
@return array
431712
public function request($service, $params = array(), $timeoutMs = 3000) {
        $this->url = $this->host . '?service=' . $service;
        $params = array_merge($this->moreParams, $params);

        $apiRs = $this->doRequest($this->url, $params, $timeoutMs);

        if ($apiRs === FALSE) {
            $this->ret = 404;
            $this->msg = T('time out');

            \PhalApi\DI()->logger->debug('task request api time out', array('url' => $this->url));

            return $this->getData();
        }

        $rs = json_decode($apiRs, true);

        if (empty($rs) || !isset($rs['ret'])) {
            $this->ret = 500;
            $this->msg = \PhalApi\T('nothing return or illegal json: {rs}', array('rs' => $apiRs));
            return $this->getData();
        }

        $this->ret = $rs['ret'];
        $this->data = $rs['data'];
        $this->msg = $rs['msg'];

        return $this->getData();
    }
75006
public function index($params = [])
    {
        // Set the filters
        $params = (!empty($params))? $params : $this->app->request->input();

        // Get records
        $this->model->params = $params;
        $result = $this->model->search($params)->get();

        // Get pagination and number of records
        $pagination = array_merge(
            ['records' => $this->model->search($params)->count()],
            $this->model->pagination()
        );

        // Return results
        return [
            'success' => true,
            'paging' => $pagination,
            'data' => $result
        ];
    }
357730
public function wait_for_response($requestId, $timeoutMs = 0) {

        if (!isset($this->_requests[$requestId])) {
            throw new \Exception('Invalid request id given');
        }

        // If we already read the response during an earlier call for different id, just return it
        if ($this->_requests[$requestId]['state'] == self::REQ_STATE_OK
            || $this->_requests[$requestId]['state'] == self::REQ_STATE_ERR
            ) {
            return $this->_requests[$requestId]['response'];
        }

        if ($timeoutMs > 0) {
            // Reset timeout on socket for now
            $this->set_ms_timeout($timeoutMs);
        } else {
            $timeoutMs = $this->_readWriteTimeout;
        }

        // Need to manually check since we might do several reads none of which timeout themselves
        // but still not get the response requested
        $startTime = microtime(true);

        do {
            $resp = $this->readPacket();

            if ($resp['type'] == self::STDOUT || $resp['type'] == self::STDERR) {
                if ($resp['type'] == self::STDERR) {
                    $this->_requests[$resp['requestId']]['state'] = self::REQ_STATE_ERR;
                }
                $this->_requests[$resp['requestId']]['response'] .= $resp['content'];
            }
            if ($resp['type'] == self::END_REQUEST) {
                $this->_requests[$resp['requestId']]['state'] = self::REQ_STATE_OK;
                if ($resp['requestId'] == $requestId) { 
                    break;
                }
            }
            if (microtime(true) - $startTime >= ($timeoutMs * 1000)) {
                // Reset
                $this->set_ms_timeout($this->_readWriteTimeout);
                throw new \Exception('Timed out');
            }
        } while ($resp);

        if (!is_array($resp)) {
            $info = stream_get_meta_data($this->_sock);

            // We must reset timeout but it must be AFTER we get info
            $this->set_ms_timeout($this->_readWriteTimeout);

            if ($info['timed_out']) {
                throw new TimedOutException('Read timed out');
            }

            if ($info['unread_bytes'] == 0
                    && $info['blocked']
                    && $info['eof']) {
                throw new ForbiddenException('Not in white list. Check listen.allowed_clients.');
            }

            throw new \Exception('Read failed');
        }

        // Reset timeout
        $this->set_ms_timeout($this->_readWriteTimeout);

        switch (ord($resp['content']{4})) {
            case self::CANT_MPX_CONN:
                throw new \Exception('This app can\'t multiplex [CANT_MPX_CONN]');
                break;
            case self::OVERLOADED:
                throw new \Exception('New request rejected; too busy [OVERLOADED]');
                break;
            case self::UNKNOWN_ROLE:
                throw new \Exception('Role value not known [UNKNOWN_ROLE]');
                break;
            case self::REQUEST_COMPLETE:
                return $this->_requests[$requestId]['response'];
        }
    }
792215
public function getByTime(Models\ByTimeParams $params)
    {
        $resource = 'bytime';
        $response = $this->sendGetRequest($resource, $params->toArray());
        $dataResponse = new Models\ByTimeData($response);
        return $dataResponse;
    }
691434
@SuppressWarnings("unused")
    public static Query createWithTimeout(Service service, Domain domain, int timeout) {
        return new Query(service, domain, timeout);
    }
1232968
public function getTotalTimeoutMs()
    {
        $field = EnumRequestOption::TOTAL_TIMEOUT_MS;
        return isset($this->options[$field]) ? $this->options[$field] : 0;
    }
891331
protected function _getServices($services)
    {
        if ($services) {
            foreach ($services as $index => $service) {
                if (!$this->_di->has($service)) {
                    if ($this->_di->has($service . 'Mongodb')) {
                        $services[$index] = $service . 'Mongodb';
                    } elseif ($this->_di->has($service . '_mongodb')) {
                        $services[$index] = $service . '_mongodb';
                    } else {
                        $this->console->warn(['`:service` service is not exists: ignoring', 'service' => $service]);
                        unset($services[$index]);
                    }
                }
            }
        } else {
            $services = [];
            foreach ($this->configure->components as $service => $config) {
                $config = json_encode($config, JSON_UNESCAPED_SLASHES);
                if (preg_match('#mongodb://#', $config)) {
                    $services[] = $service;
                }
            }
        }

        return $services;
    }
1103719
public function prepareRequest($params = 'default')
    {
        if (is_string($params)) {
            // 载入请求模板
            $params = RequestTemplate::loadTemplate($this->getModule(), $this->getAction(), $params);
        } elseif ( ! is_array($params)) {
            $params = array();
        }

        $params['apiKey'] = isset($params['apiKey']) ? $params['apiKey'] : Config::get('API_KEY');
        $params['apiUser'] = isset($params['apiUser']) ? $params['apiUser'] : Config::get('API_USER');
        $this->data = $params;

        return $this;
    }
434850
public function findOne(
        $query = [],
        $fields = [],
        $timeout = 2000
    ) {
        $this->getContext()->getLog()->profileStart($this->profileName . __FUNCTION__);
        $options = [
            'socketTimeoutMS' => $timeout
        ];
        $out = $this->mongoCollection->findOne($query, $fields, $options);
        if ($out === null) {
            return [];
        }
        $this->getContext()->getLog()->profileEnd($this->profileName . __FUNCTION__);

        return $out;
    }
127810
public function soap(string $service, string $action, array $params = [])
    {
        switch ($service) {
            case "AVTransport":
            case "RenderingControl":
                $path = "MediaRenderer";
                break;
            case "ContentDirectory":
                $path = "MediaServer";
                break;
            case "AlarmClock":
            case "DeviceProperties":
            case "ZoneGroupTopology":
                $path = null;
                break;
            default:
                throw new \InvalidArgumentException("Unknown service: {$service}");
        }

        $location = "http://{$this->ip}:1400/";
        if (is_string($path)) {
            $location .= "{$path}/";
        }
        $location .= "{$service}/Control";

        $this->logger->info("sending soap request to: {$location}", $params);

        $soap = new \SoapClient(null, [
            "location"  =>  $location,
            "uri"       =>  "urn:schemas-upnp-org:service:{$service}:1",
            "trace"     =>  true,
        ]);

        $soapParams = [];
        $params["InstanceID"] = 0;
        foreach ($params as $key => $val) {
            $soapParams[] = new \SoapParam(new \SoapVar($val, \XSD_STRING), $key);
        }

        try {
            $result = $soap->__soapCall($action, $soapParams);
            $this->logger->debug("REQUEST: " . $soap->__getLastRequest());
            $this->logger->debug("RESPONSE: " . $soap->__getLastResponse());
        } catch (\SoapFault $e) {
            $this->logger->debug("REQUEST: " . $soap->__getLastRequest());
            $this->logger->debug("RESPONSE: " . $soap->__getLastResponse());
            throw new SoapException($e, $soap);
        }

        return $result;
    }
150751
protected function call_pluginfo_service(array $params) {

        $serviceurl = $this->get_serviceurl_pluginfo();
        $response = $this->call_service($serviceurl, $params);

        if ($response) {
            if ($response->info['http_code'] == 404) {
                // There is no such plugin found in the plugins directory.
                return false;

            } else if ($response->info['http_code'] == 200 and isset($response->data->status)
                    and $response->data->status === 'OK' and $response->data->apiver == self::APIVER
                    and isset($response->data->pluginfo)) {
                    return $this->validate_pluginfo_format($response->data->pluginfo);

            } else {
                debugging('cURL: Unexpected response', DEBUG_DEVELOPER);
                return false;
            }
        }

        return false;
    }
996397
public function deregisterService(...$params)
    {        
        if (empty($this->registerId)) {
            $hostName = gethostname();
            $this->registerId = sprintf('service-%s-%s', $this->registerName, $hostName);
        }

        $url = sprintf('%s:%d%s', $this->address, $this->port, self::DEREGISTER_PATH);
        $this->removeService([], $url.$this->registerId);
    }
342315
public function search($params)
    {//echo __METHOD__;var_dump($params);
        $this->load($params);//var_dump($this->titleMinLength);var_dump($this->title);var_dump($this->body);

        $modelNewsClassname = $this->module->model('News')->className();
        $query = $this->module->model('NewsQuery', [$modelNewsClassname]);//var_dump($query);exit;

        $query->orderBy(['show_from_time' => SORT_DESC]);

        //$query->alias('main')->leftJoin(['i18n' => NewsI18n::tableName()], "main.id = i18n.news_id AND i18n.lang_code = '{$this->langCodeMain}'");

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        if (!$this->validate()) {
            $query->where('0=1'); // uncomment this line if you do not want to return any records when validation fails
            return $dataProvider;
        }

        // required criterias
        $query->where(['is_visible' => true]);

        $tzShiftSec = intval(date('Z')); // server time zone shift in seconds: west UTC <0, east UTC >0
        if (!empty($tzShiftSec)) {
            $now = new Expression("DATE_SUB(NOW(), INTERVAL {$tzShiftSec} SECOND)"); // UTC time
        }
        $query->andWhere(['<=', 'show_from_time', $now])
              ->andWhere(['or',
                  ['>=', 'show_to_time', $now],
                  ['show_to_time' => null],
                  //new Expression("show_to_time IS NULL"), //?? ['show_to_time' => null],
              ]);
        // no news for current language
/*
        $query->andWhere(['not', ['title' => null]]);
        $query->andWhere(['not', ['body'  => null]]);
        $query->andWhere(['not', ['title' => ''  ]]);
        $query->andWhere(['not', ['body'  => ''  ]]);
*/
        $query->andWhere(['and',
          ['not', ['title' => null]],
          ['not', ['body'  => null]],
          ['not', ['title' => ''  ]],
          ['not', ['body'  => ''  ]],
        ]);
        if (isset($this->titleMinLength)) {
            //$lengthExpr = new Expression("LENGTH(title)"); //! length in bytes, not UTF8-symbols
            $lengthExpr = new Expression("CHAR_LENGTH(title)");
            $query->andFilterWhere(['>=', $lengthExpr, $this->titleMinLength]);
        }
        if (isset($this->bodyMinLength)) {
            //$lengthExpr = new Expression("LENGTH(body)"); //! length in bytes, not UTF8-symbols
            $lengthExpr = new Expression("CHAR_LENGTH(body)");
            $query->andFilterWhere(['>=', $lengthExpr, $this->bodyMinLength]);
        }

        // additional search criterias
        $query->andFilterWhere(['owner_id' => $this->owner_id]);
        $query->andFilterWhere(['like', 'title', $this->title]);
        $query->andFilterWhere(['like', 'body', $this->body]);

        //list($sql, $sqlParams) = Yii::$app->db->getQueryBuilder()->build($query);var_dump($sql);var_dump($sqlParams);
        return $dataProvider;
    }
720674
protected function fetchResponse($params)
    {
        $qs = http_build_query($params);
        $response = file_get_contents($this->verifyUrl . '?' . $qs);

        return json_decode($response, true);
    }
1044091
public function getJob($queues, $timeoutMs = 200) {
        $jobs = $this->getJobs($queues, 1, $timeoutMs);

        if (empty($jobs)) {
            return null;
        }

        return $jobs[0];
    }
787651
public function fallback($fallback = null, array $params = [])
    {
        if ($fallback == null) {
            App::debug($this->serviceName . '服务，当前[' . $this->getCurrentState() . ']，服务降级处理，fallback未定义');
            return null;
        }

        if (is_array($fallback) && count($fallback) == 2) {
            list($fallbackObj, $method) = $fallback;
            App::debug($this->serviceName . '服务，服务降级处理，执行fallback, class=' . get_class($fallbackObj) . ' method=' . $method);

            return $fallbackObj->$method(...$params);
        }

        return null;
    }
429335
public function goSingleGet($url = '', $query = [], $timeout = 30000, $headers = [])
    {
        if (empty($this->urlData)) {
            $this->urlData = self::parseUrl($url);
        } else {
            if (!empty($url)) {
                $this->urlData['path'] = $url;
            }
        }

        yield $this->goDnsLookup();
        $this->setHeaders($headers);

        //支持直接在url之后带参数形式的GET请求
        $q = '';
        if (!empty($this->urlData['query'])) {
            $q = ltrim($this->urlData['query'], '?');
        }

        if (!empty($query)) {
            $q .= (empty($q) ? '' : '&') . http_build_query($query) ;
        }

        return yield $this->getObject(Http::class, [$this, 'GET', $this->urlData['path'], $q, $timeout]);
    }