add tools request libs, migrate for hyperf framework

This commit is contained in:
2025-11-10 16:48:19 +08:00
parent 5b3b0c70f2
commit 08bb2af2c3
11 changed files with 749 additions and 0 deletions
@@ -0,0 +1,60 @@
<?php
namespace App\Platform\Tools;
use App\Utils\Log;
use GuzzleHttp\RetryMiddleware;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
class GuzzleRetryConfig
{
const MAX_RETRIES = 3;
public static function retryPolicy() : callable
{
return function (int $retries, RequestInterface $request, ResponseInterface $response, ?\Throwable $exception):bool
{
return
// @TODO add host check when response is redirect may cause error
$retries < self::MAX_RETRIES
&& in_array($response->getStatusCode(), [429, 500]);
};
}
public static function retryDelay() : callable
{
return function (int $retries, ResponseInterface $response): int
{
$delay = 0;
if (!$response->hasHeader('Retry-After')) {
$delay = RetryMiddleware::exponentialDelay($retries);
} else {
$retryAfter = $response->getHeaderLine('Retry-After');
$delay = $retryAfter;
if (!is_numeric($retryAfter)) {
$delay = (new \DateTime($retryAfter))->getTimestamp() - time();
}
$delay = (int)$delay * 1000;
}
$code = $response->getStatusCode();
$seconds = $delay / 1000;
$message = "请求失败, 远程服务器响应码为 $code, 此为第 $retries 次尝试,{$seconds} 秒之后重试";
dump($message);
Log::warning($message);
return $delay;
};
}
}