php使用guzzle http发送并发接口请求

在 PHP 中, Guzzle 是一个功能强大且流行的 HTTP 客户端,提供了方便的接口来发送 HTTP 请求并处理响应,本人非常喜欢这个包且重度依赖。

以下是使用 Guzzle 发送并发请求的基本示例: 

composer require guzzlehttp/guzzle;

use GuzzleHttp\Client;
use GuzzleHttp\Promise;

$client = new Client();

// 创建多个请求,请求地址可以相同,也可以不同
$promises = [
    $client->getAsync('https://api.example.com/url1'),
    $client->getAsync('https://api.example.com/url2'),
    // 添加更多的请求...
];

//或者遍历某个二维数组或结果集

foreach($list as $k=>$v) {

    $promises[$k] = $client->getAsync('https://api.example.com/url1');

}

// 发送并发请求,并等待所有请求完成(每个请求之间是异步的,因此效率非常高),返回一个响应数组
$responses = Promise\unwrap($promises);

// 处理响应
foreach ($responses as $k => $response) {
    $result = $response->getBody()->getContents();

    // $result即接口返回的body体,{code:0,message:ok,data:{}},可以使用json_decode转一下
}

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
在 Laravel 中使用 GuzzleHttp/Guzzle 发送邮件可以通过以下步骤实现: 1. 安装 GuzzleHttp/Guzzle 可以使用 Composer 进行安装: ``` composer require guzzlehttp/guzzle ``` 2. 创建邮件发送类 在 app 目录下创建一个名为 MailSender 的类,代码如下: ```php <?php namespace App; use GuzzleHttp\Client; class MailSender { protected $client; public function __construct() { $this->client = new Client([ 'base_uri' => 'https://api.sendgrid.com/v3/', 'headers' => [ 'Authorization' => 'Bearer ' . env('SENDGRID_API_KEY'), 'Content-Type' => 'application/json' ] ]); } public function send($to, $subject, $content) { $response = $this->client->request('POST', 'mail/send', [ 'json' => [ 'personalizations' => [ [ 'to' => [ [ 'email' => $to ] ] ] ], 'from' => [ 'email' => '[email protected]' ], 'subject' => $subject, 'content' => [ [ 'type' => 'text/plain', 'value' => $content ] ] ] ]); return $response->getStatusCode(); } } ``` 其中,使用 GuzzleHttp\Client 创建一个 HTTP 客户端,设置 base_uri 为 SendGrid 邮件服务的 API 地址,headers 中包含 Authorization 和 Content-Type 信息。send() 方法接受收件人邮箱地址、邮件主题和邮件内容,使用 HTTP POST 请求发送邮件。 3. 在控制器中使用 MailSender 发送邮件 在需要发送邮件的控制器中,使用 MailSender 类发送邮件,示例代码如下: ```php <?php namespace App\Http\Controllers; use App\MailSender; use Illuminate\Http\Request; class MailController extends Controller { public function send(Request $request) { $to = $request->input('to'); $subject = $request->input('subject'); $content = $request->input('content'); $mailSender = new MailSender(); $statusCode = $mailSender->send($to, $subject, $content); return response()->json(['status' => $statusCode]); } } ``` 在 send() 方法中,从请求中获取收件人邮箱地址、邮件主题和邮件内容,然后实例化 MailSender 类并调用 send() 方法发送邮件。 4. 配置 SendGrid API 密钥 在 .env 文件中添加 SendGrid API 密钥: ``` SENDGRID_API_KEY=your_api_key_here ``` 至此,使用 GuzzleHttp/Guzzle 发送邮件的配置就完成了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值