百分百源码网-让建站变得如此简单! 登录 注册 签到领金币!

主页 | 如何升级VIP | TAG标签

当前位置: 主页>网站教程>网页制作> PHP网络要求插件Guzzle运用
分享文章到:

PHP网络要求插件Guzzle运用

发布时间:09/01 来源:未知 浏览: 关键词:
在写后台代码时,幸免不了需要与其他第三方接口交互,如向效劳号下发模板新闻,有时大概需要下发超越 10 万条。这时不得不思考使用异步和「多线程」的网络恳求。

今天向 PHP 工程师们引荐一个 Guzzle 插件。

Guzzle

Guzzle 是一个 PHP 的 HTTP 客户端,用来得心应手地发送恳求,并集成到我们的 WEB 效劳上。

接口简便:构建查询语句、POST 恳求、分流上传下载大文件、使用 HTTP cookies、上传 JSON 数据等等。

发送同步或异步的恳求均使用雷同的接口。

使用 PSR-7 接口来恳求、响应、分流,同意你使用其他兼容的 PSR-7 类库与 Guzzle 共同开发。

抽象了底层的 HTTP 传输,同意你改动环境乃至其他的代码,如:对 cURL与 PHP 的流或 socket 并非重度依靠,非堵塞事件轮回。

中心件系统同意你创立构成客户端行动。

安置 Guzzle

本文结合 Laravel 项目介绍 Guzzle 根本使用,所以使用 composer 来安置 Guzzle 再适合不外了,并且 Guzzle 官网也引荐使用 composer 来安置。

composer require guzzlehttp/guzzle:~6.0
// 或者
php composer.phar require guzzlehttp/guzzle:~6.0

发送简便的 POST 恳求

拜访第三方接口,根本上都是 POST 恳求为主。如你想做一个简便的智能谈天工具,这时候可以借助图灵机器人 API,发送一个 POST 恳求猎取主动答复内容,直接上代码:

<?php
namespace App\Http\Controllers;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
class GuzzleUseController extends Controller {
    public function tuling(Request $request) {
        $params = [
            'key' => '*****',
            'userid' => 'yemeishu'
        ];
        $params['info'] = $request->input('info', '你好吗');
        $client = new Client();
        $options = json_encode($params, JSON_UNESCAPED_UNICODE);
        $data = [
            'body' => $options,
            'headers' => ['content-type' => 'application/json']
        ];
        // 发送 post 恳求
        $response = $client->post('http://www.tuling123.com/openapi/api', $data);
        $callback = json_decode($response->getBody()->getContents());
        return $this->output_json('200', '测试图灵机器人返回结果', $callback);
    }
}

Guzzle client->post 函数还是很简便的,只需要拜访的接口,和恳求的参数,参数中主要包括:body、headers、query等,详细可参照

http://guzzle-cn.readthedocs.io/zh_CN/latest/quickstart.html#id8

测试下:

6302-8a23f04d4eb24a12.jpg

6302-2f9f5585e3f021f6.jpg

注:图灵机器人还是很智能的,按照雷同的 userid 能够识别上下文,做到智能谈天的。

发送异步的 POST 恳求

在 PHP 开发中主如果「面向历程」式的开发方式,但恳求第三方接口时,有时候并不需要等候第三方接口返回结果才连续施行。如会员购置成功时,我们需要向短信接口,发送一个 post 恳求,由短信平台发送一条短信给会员,告知会员支付成功了,由于这类「提示新闻」属于「额外的附加功效」,并不需要在会员支付时「知道」有没有发送提示成功。

这时候可以使用 Guzzle 的异步恳求功效,直接看代码:

public function sms(Request $request) {
    $code = $request->input('code');
    $client = new Client();
    $sid = '9815b4a2bb6d5******8bdb1828644f2';
    $time = '20171029173312';
    $token = 'af8728c8bc*******12019c680df4b11c';

    $sig =  strtoupper(md5($sid.$token.$time));

    $auth = trim(base64_encode($sid . ":" . $time));

    $params = ['templateSMS' => [
            'appId' => '12b43**********0091c73c0ab',
            'param' => "coding01,$code,30",
            'templateId' => '3***3',
            'to' => '17689974321'
        ]
    ];
    $options = json_encode($params, JSON_UNESCAPED_UNICODE);
    $data = [
        'query' => [
            'sig' => $sig
        ],
        'body' => $options,
        'headers' => [
            'content-type' => 'application/json',
            'Authorization' => $auth
        ]
    ];

    // 发送 post 恳求
    $promise = $client->requestAsync('POST', 'https://api.ucpaas.com/2014-06-30/Accounts/9815b4a2bb6d5******8bdb1828644f2/Messages/templateSMS', $data);

    $promise->then(
        function (ResponseInterface $res) {
            Log::info('---');
            Log::info($res->getStatusCode() . "\n");
            Log::info($res->getBody()->getContents() . "\n");
        },
        function (RequestException $e) {
            Log::info('-__-');
            Log::info($e->getMessage() . "\n");
        }
    );
    $promise->wait();

    return $this->output_json('200', '测试短信 api', []);
}

先返回接口数据:

6302-95ec6d7a688f1072.jpg

然后再输出 Log:

[2017-10-29 09:53:14] local.INFO: ---  
[2017-10-29 09:53:14] local.INFO: 200
  
[2017-10-29 09:53:14] local.INFO: {"resp":{"respCode":"000000","templateSMS":{"createDate":"20171029175314","smsId":"24a93f323c9*****8608568"}}}

最后收到短信信息:

微信截图_20200501093336.png

发送多线程异步 POST 恳求

「发送多线程异步 POST 恳求」在许多场合中使用到的,如:双十一快到了,可以做一些回馈老会员的活动,这是就需要大量的向老会员推送一条模板新闻,告诉会员参与哪些活动的。这时候就需要用到多线程异步恳求微信公众号接口。

直接上代码:

public function send($templateid, $openid, $url, $data) {
        $client = $this->bnotice->getHttp()->getClient();

        $requests = function ($open_ids) use ($templateid, $url, $data) {
            foreach($open_ids as $v){
                try {
                    yield $this->bnotice
                        ->template($templateid)
                        ->to($v)
                        ->url($url)
                        ->data($data)
                        ->request();
                } catch(Exception $e) {
                    Log::error('sendtemplate:'.$e->getMessage());
                }
            }
        };

        $pool = new Pool($client, $requests($openid), [
            'concurrency' => 16,
            'fulfilled' => function ($response, $index) {
            },
            'rejected' => function ($reason, $index) {
            },
        ]);

        $promise = $pool->promise();

        $promise->wait();
    }

其中 request 办法:

public function request($data = [])
    {
        $params = array_merge([
            'touser' => '',
            'template_id' => '',
            'url' => '',
            'topcolor' => '',
            'miniprogram' => [],
            'data' => [],
        ], $data);
        
        $required = ['touser', 'template_id'];

        foreach ($params as $key => $value) {
            if (in_array($key, $required, true) && empty($value) && empty($this->message[$key])) {
                throw new InvalidArgumentException("Attribute '$key' can not be empty!");
            }

            $params[$key] = empty($value) ? $this->message[$key] : $value;
        }

        $params['data'] = $this->formatData($params['data']);

        $this->message = $this->messageBackup;

        $options = json_encode ( $params,  JSON_UNESCAPED_UNICODE);
        $data = [
            'query' => [
                'access_token' => $this->getAccessToken()->getToken()
            ],
            'body' => $options,
            'headers' => ['content-type' => 'application/json']
        ];
        return function() use ($data) {
            return $this->getHttp()->getClient()->requestAsync('POST', $this::API_SEND_NOTICE, $data);
        };
    }

Guzzle 多线程异步恳求原型函数,使用 GuzzleHttp\Pool 对象

use GuzzleHttp\Pool;use GuzzleHttp\Client;use GuzzleHttp\Psr7\Request;$client = new Client();$requests = function ($total) {
    $uri = 'http://127.0.0.1:8126/guzzle-server/perf';
    for ($i = 0; $i < $total; $i++) {
        yield new Request('GET', $uri);
    }};$pool = new Pool($client, $requests(100), [
    'concurrency' => 5,
    'fulfilled' => function ($response, $index) {
        // this is delivered each successful response
    },
    'rejected' => function ($reason, $index) {
        // this is delivered each failed request
    },]);// Initiate the transfers and create a promise$promise = $pool->promise();// Force the pool of requests to complete.$promise->wait();

总结

有了 Guzzle,极大利便了我们并发异步恳求第三方接口。假如时间同意,我们可以看看 Guzzle 源代码,看看是怎样实现的。

引荐教程:《PHP教程》

以上就是PHP网络恳求插件Guzzle使用的具体内容,更多请关注百分百源码网其它相关文章!

打赏

打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

百分百源码网 建议打赏1~10元,土豪随意,感谢您的阅读!

共有151人阅读,期待你的评论!发表评论
昵称: 网址: 验证码: 点击我更换图片
最新评论

本文标签

广告赞助

能出一分力是一分吧!

订阅获得更多模板

本文标签

广告赞助

订阅获得更多模板