small / swoole-symfony-http-client
基于Swoole的Symfony HTTP客户端实现,符合Symfony HttpClientInterface规范,用于高性能异步HTTP请求
1.0.0
2024-09-24 18:26 UTC
Requires
- php: >=8.3
- symfony/http-client-contracts: 3.*
- upscale/ext-openswoole: v22.1.*
- upscale/ext-swoole: 5.1.*
Requires (Dev)
Suggests
- ext-openswoole: >=22.1.2
- ext-swoole: >=5.1.4
- openswoole/core: 22.1.5
- symfony/http-client: 7.*
This package is not auto-updated.
Last update: 2024-09-25 00:59:05 UTC
README
Small Swoole Symfony Http Client
Small Swoole Symfony Http Client是一个使用Swoole构建的定制HTTP客户端,旨在完全兼容Symfony的HttpClient组件。它提供异步、非阻塞的HTTP客户端,支持重定向、重试、超时等多种功能。
要求
- PHP 8.3或更高版本
- Swoole 5.x或更高版本或OpenSwoole 22.1.2或更高版本
- Composer
安装
首先,确保您系统上已安装Swoole。您可以通过PECL安装它
pecl install swoole
接下来,使用Composer安装SwooleHttpClient及其依赖项
composer require small/swoole-symfony-http-client
使用方法
基本GET请求
use Small\SwooleSymfonyHttpClient\SwooleHttpClient;
$client = new SwooleHttpClient();
$response = $client->request('GET', 'https://example.com');
echo $response->getContent();
基本POST请求
$client = new SwooleHttpClient();
$response = $client->request('POST', 'https://example.com/api', [
'body' => ['key' => 'value']
]);
echo $response->getContent();
发送JSON数据
$client = new SwooleHttpClient();
$response = $client->request('PUT', 'https://example.com/api', [
'json' => ['name' => 'John', 'age' => 30]
]);
echo $response->getContent();
处理超时
$client = new SwooleHttpClient();
try {
$response = $client->request('GET', 'https://example.com/slow-endpoint', [
'timeout' => 2 // in seconds
]);
} catch (Small\SwooleSymfonyHttpClient\Exception\TimeoutException $e) {
echo "Request timed out!";
}
处理重定向
$client = new SwooleHttpClient();
$response = $client->withOptions(['max_redirects' => 3])
->request('GET', 'https://example.com/redirect');
echo $response->getContent();
基本身份验证
$client = new SwooleHttpClient();
$response = $client->withOptions([
'auth_basic' => ['username' => 'admin', 'password' => 'password']
])->request('GET', 'https://example.com/auth');
echo $response->getContent();
Bearer令牌身份验证
$client = new SwooleHttpClient();
$response = $client->withOptions([
'auth_bearer' => 'your-bearer-token'
])->request('GET', 'https://example.com/protected');
echo $response->getContent();
在失败的请求上重试
$client = new SwooleHttpClient();
$response = $client->withOptions([
'retry_failed' => 3 // Retry up to 3 times on failure
])->request('GET', 'https://example.com/flaky-endpoint');
echo $response->getContent();
自定义头
$client = new SwooleHttpClient();
$response = $client->withOptions([
'headers' => [
'Accept' => 'application/json',
'Authorization' => 'Bearer token'
]
])->request('GET', 'https://example.com/api');
echo $response->getContent();
运行测试
构建容器
docker compose up -d
并用composer运行
bin/composer unit-tests
许可证
本项目采用MIT许可证。有关详细信息,请参阅LICENSE文件。