PHP网络请求插件Guzzle使用-php教程

资源魔 45 0
正在写后盾代码时,防止没有了需求与其余第三方接口交互,如向效劳号下发模板音讯,有时可能需求下发超越 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应用的具体内容,更多请存眷资源魔其它相干文章!

标签: php php开发教程 php开发资料 php开发自学

抱歉,评论功能暂时关闭!