null, 'httpHeaders' => [], 'requestTimeout' => 3000, 'retries' => 3, 'decideRetryFunction' => null, 'delayFunction' => null, 'calcDelayFunction' => null ]; $this->httpHandler = $config['httpHandler'] ?: HttpHandlerFactory::build(); $this->httpHeaders = $config['httpHeaders']; $this->retries = $config['retries']; $this->decideRetryFunction = $config['decideRetryFunction'] ?: $this->getDecideRetryFunction(); $this->calcDelayFunction = $config['calcDelayFunction'] ?: [$this, 'calculateDelay']; $this->delayFunction = $config['delayFunction'] ?: static function ($delay) { usleep($delay); }; } /** * 发送请求,并接受返回 * * @param RequestInterface $request * @param array $options 请求的配置参数 * @return Response * @throws Exception */ public function sendAndReceive(RequestInterface $request, array $options = []) { try { $delayFunction = $this->delayFunction; $calcDelayFunction = $this->calcDelayFunction; $retryAttempt = 0; while (true) { try { return call_user_func_array($this->httpHandler, [$this->applyHeaders($request), $options]); } catch (Exception $exception) { if ($this->decideRetryFunction) { if (!call_user_func($this->decideRetryFunction, $exception)) { throw $exception; } } if ($retryAttempt >= $this->retries) { break; } $delayFunction($calcDelayFunction($retryAttempt)); $retryAttempt++; } } throw $exception; } catch (Exception $ex) { throw $ex; } } /** * 将头部信息添加到请求对象中 * * @param $request 请求对象 * @return RequestInterface */ private function applyHeaders($request) { return Utils::modifyRequest($request, ['set_headers' => $this->httpHeaders]); } /** * 根据重试次数计算下次重试延迟时间 * * @param int $attempt 重试次数 * @return int */ public static function calculateDelay($attempt) { return min( mt_rand(0, 1000000) + (pow(2, $attempt) * 1000000), self::MAX_DELAY_MICROSECONDS ); } }