Laravel中用GuzzleHttp

今天項目中用到GuzzleHttp,開始不知道怎麼用,其實還是很簡單的。
直接在項目根目錄,輸入以下命令

composer require guzzlehttp/guzzle

等下載安裝好,在vendor文件夾下,有一個guzzle目錄,此文件夾就是guzzlehttp的package了。
如何使用,可以參考官方文檔http://docs.guzzlephp.org/en/latest/
下面這段代碼就是官網文檔中的一段

$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 個請求,用戶 NauxLiuGithub ID 爲:9570112
請求第 0 個請求,用戶 CycloneAxeGithub ID 爲:6268176
請求第 1 個請求,用戶 appleboy 的 Github ID 爲:21979
請求第 2 個請求,用戶 AufreeGithub ID 爲:5310542
請求第 3 個請求,用戶 lifesign 的 Github ID 爲:2189610
請求第 4 個請求,用戶 overtrue 的 Github ID 爲:1472352
請求結束!
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章