当前位置:网站首页>PHP implements non blocking (concurrent) request mode through native curl
PHP implements non blocking (concurrent) request mode through native curl
2022-07-25 14:45:00 【Blown leaves】
List of articles
Antecedents feed
In actual development , There are often scenarios where a program needs to perform multiple operations at the same time , If the request method is inappropriate in such scenarios , In the later logic, the increase of accumulated data will affect the response efficiency of the program , Generally, non blocking mode can be used in this scenario , Here, it can also be understood as concurrency mode .
What are blocking and non blocking
Blocking : It means that the application executes IO Operation needs to be completed completely before returning to user space
Non blocking : It means that the application executes IO A status value is returned to the user immediately after the operation is called , No need to wait IO Operation complete .
How to implement non blocking mode
PHP There are many ways to implement non blocking mode , For example PHP-FPM Use function in mode fastcgi_finish_request() perhaps fsockopen() And so on , Native will be used here CURL To implement the non blocking mode of the request .
Realization way
The main implementation core is actually the use of CURL Medium curl_multi_* Function to send an asynchronous request
- Create class file
MultiHttpRequest.php, The code implementation is as follows
<?php
class MultiHttpRequest
{
public $requests = [];
/** * Set the request url * * @param $requests * @return $this */
public function setRequests($requests) {
$this->requests = $requests;
return $this;
}
/** * Send a request * * @return array|false */
public function request()
{
if(!is_array($this->requests) or count($this->requests) == 0){
return false;
}
$curl = $response = [];
$handle = curl_multi_init();
foreach($this->requests as $k => $v){
$url = isset($v['url']) ? $v['url'] : '';
$postData = isset($v['postData']) ? $v['postData'] : [];
$header = isset($v['header']) ? $v['header'] : [];
$timeOut = isset($v['timeOut']) ? $v['timeOut'] : 1;
$proxy = isset($v['proxy']) ? $v['proxy'] : '';
$curl[$k] = $this->buildCurlObject($url, $postData, $header, $timeOut, $proxy);
curl_multi_add_handle($handle, $curl[$k]);
}
$this->execHandle($handle);
foreach ($this->requests as $key => $val){
$response[$key] = curl_multi_getcontent($curl[$key]);
curl_multi_remove_handle($handle, $curl[$key]);
curl_close($curl[$key]);
}
curl_multi_close($handle);
return $response;
}
/** * Construct request * * @param $url * @param $postData * @param $header * @param $timeOut * @param $proxy * @return false|resource */
private function buildCurlObject($url, $postData, $header, $timeOut, $proxy) {
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_TIMEOUT, (int)$timeOut);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
// Configure agent
if (!empty($proxy))
curl_setopt($curl, CURLOPT_PROXY, $proxy);
// Merge request header information
if(!empty($header))
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
// Whether it is post request
if(!empty($postData) && is_array($postData)){
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($postData));
}
// Whether it is https
if(stripos($url,'https') === 0){
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
}
return $curl;
}
/** * Execute batch handle * * @param $handle * @return void */
private function execHandle($handle)
{
$active = true;
$mrc = CURLM_OK;
while ($active && $mrc == CURLM_OK) {
do {
$mrc = curl_multi_exec($handle, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
if (curl_multi_select($handle) == -1) {
usleep(100);
}
}
}
}
- Calling procedure , Non blocking request
<?php
$response = new MultiHttpRequest();
$url = [
['url' => 'https://www.baidu.com',
'postData' =>['aaa'=>1],
'header' => [
"Content-Type:application/Json",
"X-Requested-With:XMLhttpRequest"
],
'timeOut' => 2,
'proxy' => '127.0.0.1'
],
['url' => 'https://www.baidu.com'],
['url' => 'https://www.baidu.com'],
];
$response = $this->setRequests($url)->request();
var_dump($response);
边栏推荐
- OverTheWire-Bandit
- awk从入门到入土(23)awk内置变量ARGC、ARGC--命令行参数传递
- thymeleaf通过样式控制display是否显示
- 006 operator introduction
- IP address classification, which determines whether a network segment is a subnet supernetwork
- PS making and loading GIF pictures tutorial
- D2. picking carrots (hard version) (one question per day)
- The input input box of H5 page pops up the numeric keypad, which needs to support decimal points
- 微信公众号正式环境上线部署,第三方公众平台接入
- The solution to the problem that the progress bar of ros2 installation connext RMW is stuck at 13%
猜你喜欢

机械制造业数字化新“引擎”供应链协同管理系统助力企业精细化管理迈上新台阶

GameFramework制作游戏(一)

32 use of chrome debugging tools
![优质数对的数目[位运算特点+抽象能力考察+分组快速统计]](/img/c9/8f8f0934111f7ae8f8abd656d92f12.png)
优质数对的数目[位运算特点+抽象能力考察+分组快速统计]

Gameframework making games (II) making UI interface

37 元素模式(行内元素,块元素,行内块元素)

The concept and operation rules of calculus of variations

I2C device driver hierarchy

Development of uni app offline ID card identification plug-in based on paddleocr

GameFramework制作游戏(二)制作UI界面
随机推荐
BIO、NIO、AIO示例
变分(Calculus of variations)的概念及运算规则
sudo rosdep init Error ROS安装问题解决方案
IP address classification, which determines whether a network segment is a subnet supernetwork
kibana操作es
41 图片背景综合-五彩导航图
27 classification of selectors
[MySQL must know and know] trigger | permission management
Software testing -- 1. Outline of software testing knowledge
基于PaddleOCR开发uni-app离线身份证识别插件
Vs2017 large factory ERP management system source code factory general ERP source code
MySQL 45讲 | 06 全局锁和表锁 :给表加个字段怎么有这么多阻碍?
thymeleaf设置disabled
Thymeleaf controls whether display is displayed through style
Gson and fastjson
I2C设备驱动程序的层次结构
MySQL 45 talks about | 06 global locks and table locks: Why are there so many obstacles to adding a field to a table?
C language and SQL Server database technology
机械制造业数字化新“引擎”供应链协同管理系统助力企业精细化管理迈上新台阶
spark参数调整调优