带你学习hyperf-5.2 Guzzle Http客户端

5.2 Guzzle Http客户端

安装composer包

composer require hyperf/guzzle

配置

使用

<?php
namespace AppController;

class IndexController extends AbstractController
{
    /**
     * @HyperfDiAnnotationInject()
     * @var HyperfGuzzleClientFactory
     */
    protected $clientFactory;

    public function index()
    {
        $options = [
            // guzzle http里的配置信息
            'base_uri' => 'http://127.0.0.1:8888',
            'handler' => GuzzleHttpHandlerStack::create(new HyperfGuzzleCoroutineHandler()),
            'timeout' => 5,
            // swoole的配置信息,内容会覆盖guzzle http里的配置信息
            'swoole' => [
                'timeout' => 10,
                'socket_buffer_size' => 1024 * 1024 * 2,
            ],
        ];
        $client = $this->clientFactory->create($options);

        $response = $client->get("/test");

        return [
            'code' => $response->getStatusCode(),
            'body' => $response->getBody()->getContents(),
            'content' => $response->getReasonPhrase()
        ];
    }
}

输出
 {
    "code": 200,
    "body": "{"key":"value"}",
    "content": "OK"
}

使用(使用连接池)

<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://doc.hyperf.io
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace AppController;

class IndexController extends AbstractController
{
    /**
     * @HyperfDiAnnotationInject()
     * @var HyperfGuzzleClientFactory
     */
    protected $clientFactory;

    public function index()
    {
        $options = [
            // guzzle http里的配置信息
            'base_uri' => 'http://127.0.0.1:8888',
            'handler' => (new HyperfGuzzleHandlerStackFactory())->create(),
            'timeout' => 5,
            // swoole的配置信息,内容会覆盖guzzle http里的配置信息
            'swoole' => [
                'timeout' => 10,
                'socket_buffer_size' => 1024 * 1024 * 2,
            ],
        ];
        $client = make(GuzzleHttpClient::class, [
            'config' => $options
        ]);
        $response = $client->get("/test");

        return [
            'code' => $response->getStatusCode(),
            'body' => $response->getBody()->getContents(),
            'content' => $response->getReasonPhrase()
        ];
    }
}

zhaohao

大家好,欢迎来到赵豪博客!赵豪,94年生人,PHP程序员一枚,因为对PHP开发有着相对比较浓厚的兴趣,所以现在从事着PHP程序员的工作。 今天再次开通这个博客,这里将记录我的职业生涯的点点滴滴,感谢来访与关注!如果我的博客能给您带来一些帮助那真是一件非常荣幸的事情~

相关推荐

发表评论

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

微信扫一扫

微信扫一扫

微信扫一扫,分享到朋友圈

带你学习hyperf-5.2 Guzzle Http客户端
返回顶部

显示

忘记密码?

显示

显示

获取验证码

Close