Laravel中用GuzzleHttp

Laravel中用GuzzleHttp

今天项目中用到GuzzleHttp,开始不知道怎么用,其实还是很简单的。
直接在项目根目录,输入以下命令

composer require guzzlehttp/guzzle

等下载安装好,在vendor文件夹下,有一个guzzle目录,此文件夹就是guzzlehttp的package了。
如何使用,可以参考官方文档http://docs.guzzlephp.org/en/latest/

guzzle中文文档:http://guzzle-cn.readthedocs.io/zh_CN/latest/overview.html
下面这段代码就是官网文档中的一段

$client = new GuzzleHttp\Client();
$res = $client->request('GET', 'https://api.github.com/user', [
    'auth' => ['user', 'pass']
]);
echo $res->getStatusCode();
// "200"
echo $res->getHeader('content-type');
// 'application/json; charset=utf8'
echo $res->getBody();
// {"type":"User"...'

// Send an asynchronous request.
$request = new \GuzzleHttp\Psr7\Request('GET', 'http://httpbin.org');
$promise = $client->sendAsync($request)->then(function ($response) {
    echo 'I completed! ' . $response->getBody();
});
$promise->wait();

 


我在项目中,已经使用了form表单post,异步请求等等。
这篇文章还是挺有意思的《Laravel 下使用 Guzzle 编写多线程爬虫实战》,代码啥都有,虽然是个小玩意,但能学到很多东西。
比如:

  1. 在Laravel中如何创建命令
  2. 怎么用多线程

贴一下代码

<?php namespace App\Console\Commands;

use GuzzleHttp\Client;
use GuzzleHttp\Pool;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Exception\ClientException;
use Illuminate\Console\Command;

class MultithreadingRequest extends Command
{
    private $totalPageCount;
    private $counter        = 1;
    private $concurrency    = 7;  // 同时并发抓取

    private $users = ['CycloneAxe', 'appleboy', 'Aufree', 'lifesign',
                        'overtrue', 'zhengjinghua', 'NauxLiu'];

    protected $signature = 'test:multithreading-request';
    protected $description = 'Command description';

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        $this->totalPageCount = count($this->users);

        $client = new Client();

        $requests = function ($total) use ($client) {
            foreach ($this->users as $key => $user) {

                $uri = 'https://api.github.com/users/' . $user;
                yield function() use ($client, $uri) {
                    return $client->getAsync($uri);
                };
            }
        };

        $pool = new Pool($client, $requests($this->totalPageCount), [
            'concurrency' => $this->concurrency,
            'fulfilled'   => function ($response, $index){

                $res = json_decode($response->getBody()->getContents());

                $this->info("请求第 $index 个请求,用户 " . $this->users[$index] . " 的 Github ID 为:" .$res->id);

                $this->countedAndCheckEnded();
            },
            'rejected' => function ($reason, $index){
                $this->error("rejected" );
                $this->error("rejected reason: " . $reason );
                $this->countedAndCheckEnded();
            },
        ]);

        // 开始发送请求
        $promise = $pool->promise();
        $promise->wait();
    }

    public function countedAndCheckEnded()
    {
        if ($this->counter < $this->totalPageCount){
            $this->counter++;
            return;
        }
        $this->info("请求结束!");
    }
}

 

运行结果如下:

$ php artisan test:multithreading-request
请求第 5 个请求,用户 zhengjinghua 的 Github ID 为:3413430
请求第 6 个请求,用户 NauxLiu 的 Github ID 为:9570112
请求第 0 个请求,用户 CycloneAxe 的 Github ID 为:6268176
请求第 1 个请求,用户 appleboy 的 Github ID 为:21979
请求第 2 个请求,用户 Aufree 的 Github ID 为:5310542
请求第 3 个请求,用户 lifesign 的 Github ID 为:2189610
请求第 4 个请求,用户 overtrue 的 Github ID 为:1472352
请求结束!

 

 

 

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xhanfei/article/details/51908629
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/113127.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • Java链表——遍历、查找、求链表长度

    Java链表——遍历、查找、求链表长度1.遍历非常简单的一段代码,只需要在节点不为空时,一个接一个地输出即可。publicvoidErgodic(){ ListNodeindexNode=head; while(indexNode.getNext()!=null){ System.out.print(indexNode.getVal()+””); indexNode=indexNode.getNext(); } }2.查找我们来做一个对值的查找…

    2022年5月13日
    62
  • idea2022激活码截至2022年【中文破解版】2022.02.01

    (idea2022激活码截至2022年)本文适用于JetBrains家族所有ide,包括IntelliJidea,phpstorm,webstorm,pycharm,datagrip等。IntelliJ2021最新激活注册码,破解教程可免费永久激活,亲测有效,下面是详细链接哦~https://javaforall.net/100143.html…

    2022年3月31日
    1.8K
  • Spring通过SchedulerFactoryBean实现调度任务的配置(定时器)

    Spring通过SchedulerFactoryBean实现调度任务的配置(定时器)<?xmlversion=”1.0″encoding=”UTF-8″?><beansxmlns=”http://www.springframework.org/schema/beans”xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”xmlns:contex…

    2022年5月10日
    42
  • 微信聊天记录数据分析「建议收藏」

    目录一、项目背景二、数据准备三、数据预处理及描述性统计四、数据分析1.聊天时间分布图2.高频词汇统计3.词云图展示五、其它探索性分析一、项目背景2021年2月20日我和我女朋友第一次见面,之后开启了我们两个人的故事,时隔一年我想将我们的聊天记录提取出来进行简单的数据分析一下。微信里面有2021年4月20日至2022年2月20日的聊天记录,一共十个月的数据。二、数据准备在网上有许多文章关于可以找到关于…

    2022年4月12日
    453
  • thinkphp访问路径_thinkphp laravel

    thinkphp访问路径_thinkphp laravel下载地址:http://code.google.com/p/kindeditor/downloads/list基本配置:KE.show({id:’your_editor_id’,width:’700px’,height:’400px’});首先引入kindeditor.js文件;用show方法传入一个数组,里面是你的配置信息,然后

    2022年10月12日
    3
  • python+selenium环境搭建_pycharm配置anaconda环境

    python+selenium环境搭建_pycharm配置anaconda环境最近在研究python+selenium进行自动化测试。然后用的python开发工具是Pycharm。然后,今天就跟大家讲一下怎么搭建一整套的自动化测试环境。安装python首先,安装python。python可以在官网下载。安装可参考链接:http://blog.csdn.net/florachy/article/details/72769813我安装的是python3.6.0:…

    2022年8月28日
    0

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号