如何将API请求动态添加到池中,然后使用Laravel的HTTP客户端运行它?
我正在尝试使用Gmail API下载数千封电子邮件。我发现在下载大量数据时最好进行批处理请求。我想用 laravel的http client ,因为我看到它可以汇总请求,听起来正是我需要的。
但是我想动态创建池。我没有加载电子邮件(我只有Gmail ID的电子邮件,我必须再进行另一个API调用才能获取电子邮件内容)。我设法事先创建一个池:
use Illuminate\Http\Client\Pool;
$pool = new Pool();
foreach ($emails as $email) {
$pool->withToken($user->googleAccessToken()->value)->get('https://gmail.googleapis.com/gmail/v1/users/me/messages/' . $email->email_id);
}
但是后来我不知道如何使用客户端运行它,因为http :: pool
期望回电。
我尝试做类似的事情:
$user = Auth::user();
$emails = $user->emails()->where('downloaded', false)->get();
$responses = Http::pool(function(Pool $pool) {
foreach ($emails as $email) {
$pool->withToken($user->googleAccessToken()->value)->get('https://gmail.googleapis.com/gmail/v1/users/me/messages/' . $email->email_id);
}
});
dd($responses);
但是我只是得到不确定的变量$ emails
。
我想做的是从我的数据库中检索所有这些未下载的电子邮件,并以下面的脚本将100条请求发送到Gmail API(但是,如果URL动态添加):
use Illuminate\Http\Client\Pool;
use Illuminate\Support\Facades\Http;
$responses = Http::pool(fn (Pool $pool) => [
$pool->get('http://localhost/first'),
$pool->get('http://localhost/second'),
$pool->get('http://localhost/third'),
]);
I'm trying to download thousands of emails with the Gmail API. I found that it is better to batch requests when downloading a large amount of data. And I want to achieve that with Laravel's HTTP client because I saw it can pool requests and it sounds like exactly what I need.
But I want to create the pool dynamically. I have undownloaded emails (emails for which I only have a gmail id and I must make another API call to get the email content). I manage to create a pool beforehand :
use Illuminate\Http\Client\Pool;
$pool = new Pool();
foreach ($emails as $email) {
$pool->withToken($user->googleAccessToken()->value)->get('https://gmail.googleapis.com/gmail/v1/users/me/messages/' . $email->email_id);
}
but then I don't know how to run it with the client because Http::pool
expects a callback.
I tried doing something like this instead :
$user = Auth::user();
$emails = $user->emails()->where('downloaded', false)->get();
$responses = Http::pool(function(Pool $pool) {
foreach ($emails as $email) {
$pool->withToken($user->googleAccessToken()->value)->get('https://gmail.googleapis.com/gmail/v1/users/me/messages/' . $email->email_id);
}
});
dd($responses);
but I just get Undefined variable $emails
.
What I'd like to do is retrieve all these not downloaded emails from my db and send batches of 100 requests to the Gmail API, with a script like below (but with URLs added dynamically):
use Illuminate\Http\Client\Pool;
use Illuminate\Support\Facades\Http;
$responses = Http::pool(fn (Pool $pool) => [
$pool->get('http://localhost/first'),
$pool->get('http://localhost/second'),
$pool->get('http://localhost/third'),
]);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您似乎没有在闭包中包含
$emails
变量。应该是It seems that you're not including your
$emails
variable in the closure. It should be