>  기사  >  백엔드 개발  >  PHP 네트워크 요청 플러그인 Guzzle 사용

PHP 네트워크 요청 플러그인 Guzzle 사용

Guanhui
Guanhui앞으로
2020-05-01 09:40:575755검색

백그라운드 코드를 작성할 때 템플릿 메시지를 서비스 계정으로 보내는 등 다른 타사 인터페이스와 상호 작용하는 것은 불가피합니다. 때로는 100,000개 이상의 메시지를 보내야 할 수도 있습니다. 현재로서는 비동기 및 "다중 스레드" 네트워크 요청 사용을 고려해야 합니다.

오늘 저는 PHP 엔지니어들에게 Guzzle 플러그인을 추천합니다.

Guzzle

Guzzle은 쉽게 요청을 보내고 웹 서비스에 통합하는 데 사용되는 PHP HTTP 클라이언트입니다.

간단한 인터페이스: 쿼리 문 구성, POST 요청, 대용량 파일 분할 업로드 및 다운로드, HTTP 쿠키 사용, JSON 데이터 업로드 등

동일한 인터페이스를 사용하여 동기 또는 비동기 요청을 보냅니다.

PSR-7 인터페이스를 사용하여 요청하고, 응답하고, 오프로드하면 다른 호환 가능한 PSR-7 클래스 라이브러리를 사용하여 Guzzle과 함께 개발할 수 있습니다.

기본 HTTP 전송을 추상화하여 cURL 및 PHP 스트림이나 소켓에 크게 의존하지 않고 비차단 이벤트 루프와 같은 환경 및 기타 코드를 변경할 수 있습니다.

미들웨어 시스템을 사용하면 클라이언트 측 동작을 생성할 수 있습니다.

Guzzle 설치

본 글에서는 Laravel 프로젝트를 결합하여 Guzzle의 기본 사용법을 소개하므로, Guzzle 설치 시에는 Composer를 사용하는 것이 가장 적합하며, Guzzle 공식 홈페이지에서도 Composer를 사용하여 설치하는 것을 권장하고 있습니다.

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

간단한 POST 요청 보내기

타사 인터페이스에 액세스하세요. 기본적으로 POST 요청이 주요 요청입니다. 간단한 지능형 채팅 도구를 만들고 싶다면 Turing 로봇 API를 사용하여 POST 요청을 보내 자동 답변 내용을 얻을 수 있습니다. 코드로 직접 이동하세요.

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

Guzzle 클라이언트->게시 기능은 여전히 ​​매우 간단합니다. , 액세스 인터페이스와 요청 매개변수만 있으면 됩니다. 매개변수에는 주로 본문, 헤더, 쿼리 등이 포함됩니다. 자세한 내용은

http://guzzle-cn.readthedocs.io/zh_CN/latest/quickstart.html을 참조하세요. #id8

테스트 중:

PHP 네트워크 요청 플러그인 Guzzle 사용

PHP 네트워크 요청 플러그인 Guzzle 사용

참고: Turing 로봇은 여전히 ​​동일한 사용자 ID를 기반으로 컨텍스트를 식별하고 지능형 채팅을 수행할 수 있습니다.

비동기 POST 요청 보내기

PHP 개발에서는 주로 "프로세스 지향" 개발 방법이지만 타사 인터페이스를 요청할 때 타사 인터페이스를 기다릴 필요가 없는 경우도 있습니다. 실행을 계속하기 전에 결과를 반환합니다. 예를 들어 사용자의 구매가 성공하면 SMS 인터페이스에 게시물 요청을 보내야 하며 SMS 플랫폼은 사용자에게 결제가 성공했음을 알리는 문자 메시지를 보냅니다. 메시지"는 "추가 추가 기능"이며 필수가 아닙니다. 사용자가 결제할 때 알림이 성공적으로 전송되었는지 여부를 "알 수 있습니다".

이제 Guzzle의 비동기 요청 기능을 사용하여 코드를 직접 볼 수 있습니다.

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

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

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

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

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

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

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

먼저 인터페이스 데이터를 반환합니다.

PHP 네트워크 요청 플러그인 Guzzle 사용

그런 다음 로그를 출력합니다.

[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"}}}

마지막으로 SMS 메시지를 받습니다.

PHP 네트워크 요청 플러그인 Guzzle 사용

멀티 스레드 비동기 POST 요청 보내기

"멀티 스레드 비동기 POST 요청 보내기"는 다음과 같은 여러 경우에 사용됩니다. Double Eleven이 곧 출시됩니다. 이전 사용자에게 보답하기 위해 몇 가지 활동을 수행할 수 있습니다. 이전 사용자에게 일괄 피드백이 필요합니다. 템플릿 메시지를 푸시하여 사용자가 참여한 활동을 알려줍니다. 이때 다중 스레드 비동기 요청 WeChat 공식 계정 인터페이스를 사용해야 합니다.

코드로 직접 이동:

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(&#39;sendtemplate:&#39;.$e->getMessage());
                }
            }
        };

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

        $promise = $pool->promise();

        $promise->wait();
    }

요청 방법:

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

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

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

        $params[&#39;data&#39;] = $this->formatData($params[&#39;data&#39;]);

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

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

GuzzleHttpPool 객체를 사용하는 Guzzle 다중 스레드 비동기 요청 프로토타입 함수

use GuzzleHttp\Pool;use GuzzleHttp\Client;use GuzzleHttp\Psr7\Request;$client = new Client();$requests = function ($total) {
    $uri = &#39;http://127.0.0.1:8126/guzzle-server/perf&#39;;
    for ($i = 0; $i < $total; $i++) {
        yield new Request(&#39;GET&#39;, $uri);
    }};$pool = new Pool($client, $requests(100), [
    &#39;concurrency&#39; => 5,
    &#39;fulfilled&#39; => function ($response, $index) {
        // this is delivered each successful response
    },
    &#39;rejected&#39; => 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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 jianshu.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제