上一篇
想象一下:用户在你的电商网站上上传高清商品图,结果页面卡成“转圈圈大赛”冠军,甚至直接超时失败……别让这种灾难场景毁掉用户体验!今天教你用Laravel队列实现文件异步上传,再结合Guzzle的并发请求,让你的应用性能直接起飞!💻
.env
的QUEUE_CONNECTION=redis
。predis/predis
扩展:composer require predis/predis
config/database.php
)。php artisan make:job UploadFileJob
编辑UploadFileJob.php
,在handle
方法中实现文件上传逻辑:
use GuzzleHttp\Client; public function handle() { $client = new Client(); $response = $client->post('https://api.example.com/upload', [ 'multipart' => [ ['name' => 'file', 'contents' => fopen($this->file, 'r')] ] ]); // 处理响应结果 }
use App\Jobs\UploadFileJob; public function upload(Request $request) { $file = $request->file('file')->store('uploads'); UploadFileJob::dispatch($file, 'https://api.example.com/upload'); return response()->json(['message' => '上传已启动!']); }
[program:laravel-worker] process_name=%(program_name)s_%(process_num)02d command=php /path/to/artisan queue:work --tries=3 --timeout=60 autostart=true autorestart=true numprocs=4
sudo supervisorctl reread && sudo supervisorctl update
composer require guzzlehttp/guzzle
use GuzzleHttp\Client; use GuzzleHttp\Promise\Utils; $client = new Client(); $promises = [ 'api1' => $client->getAsync('https://api1.example.com'), 'api2' => $client->getAsync('https://api2.example.com'), ]; $results = Utils::settle($promises)->wait(); foreach ($results as $name => $result) { if ($result['state'] === 'fulfilled') { echo "{$name} 成功:" . $result['value']->getBody(); } else { echo "{$name} 失败:" . $result['reason']->getMessage(); } }
UploadFileJob
的handle
方法中,使用Guzzle的postAsync
方法并发上传:public function handle() { $client = new Client(); $promises = [ 's3' => $client->postAsync('https://s3.example.com/upload', [/*...*/]), 'oss' => $client->postAsync('https://oss.example.com/upload', [/*...*/]), ]; $results = Utils::settle($promises)->wait(); // 处理结果 }
numprocs
参数,根据服务器性能设置工作进程数。BLPOP
命令优化任务获取效率。timeout
和connect_timeout
,避免请求挂起。multipart
选项上传文件,减少内存占用。--tries
和--backoff
参数,实现自动重试。var uploader = WebUploader.create({ auto: true, server: '/upload', formData: { _token: '{{ csrf_token() }}' } });
通过Laravel队列和Guzzle并发请求的结合,不仅解决了文件上传的卡顿问题,还大幅提升了API请求的效率。🔥你的应用已经能够轻松应对高并发场景,用户体验直线上升!赶紧动手试试吧,有任何问题欢迎在评论区交流~💬
信息来源:
本文由 业务大全 于2025-08-26发表在【云服务器提供商】,文中图片由(业务大全)上传,本平台仅提供信息存储服务;作者观点、意见不代表本站立场,如有侵权,请联系我们删除;若有图片侵权,请您准备原始证明材料和公证书后联系我方删除!
本文链接:https://vds.7tqx.com/wenda/733331.html
发表评论