详解PHP实现异步调用的4种方法
异步调用的概念
异步调用是指在发起请求后不等待响应,而是立即返回,在后续处理中获取响应的方式。相对于同步调用,它能够提高程序的并发能力和响应速度。
在PHP中,实现异步调用有多种方法,下面将详细介绍这四种方法。
方法一:使用cURL的异步选项
cURL(Client URL Library)是一个很常用的、强大的网络请求库。在PHP中,cURL也是默认提供的扩展库之一。cURL提供了一系列选项,让我们可以在请求时设置异步选项。
下面是一个示例代码:
function request($url, $callback) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_NOSIGNAL, true); // 开启异步选项
curl_setopt($ch, CURLOPT_TIMEOUT_MS, 200); // 设置超时时间
curl_setopt($ch, CURLOPT_WRITEFUNCTION, $callback);
curl_setopt($ch, CURLOPT_FORBID_REUSE, false);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_exec($ch);
curl_close($ch);
}
function callback($ch, $content) {
echo 'result: ' . $content . PHP_EOL;
}
$url = 'https://www.example.com';
request($url, 'callback');
这个代码中,我们使用了curl_setopt函数设置了异步选项,并设置了超时时间。在请求启动后,程序不会等待响应,而是立即返回并输出result。请求的响应内容将在回调函数中输出。
方法二:使用pcntl_fork实现进程异步
在PHP中,可以使用pcntl_fork函数来创建子进程,达到异步调用的效果。子进程可以独立和父进程进行操作,这就使得程序的执行速度得到了提升。
下面是一个示例代码:
function async_request($url, $callback) {
$pid = pcntl_fork();
if ($pid === -1) {
die('fork failed');
} else if ($pid === 0) {
$content = file_get_contents($url);
call_user_func($callback, $content);
exit(0);
}
}
function callback($content) {
echo 'result: ' . $content . PHP_EOL;
}
$url = 'https://www.example.com';
async_request($url, 'callback');
这个代码中,我们使用pcntl_fork函数创建了一个子进程,子进程中请求了$url并将返回的内容传递给回调函数。在父进程中,程序不会等待子进程的完成,而是立即返回。
方法三:使用swoole扩展
Swoole是一个基于PHP的C++扩展库,提供了一些函数和类,使PHP具备类似Node.js、Go等语言的协程、异步IO等高性能特性。使用Swoole扩展可以实现高并发、低消耗的异步调用。
下面是一个示例代码:
$client = new swoole_http_client('www.example.com', 80);
$client->set([
'keep_alive' => false,
'timeout' => 10,
]);
$client->setHeaders([
'Host' => 'www.example.com',
"User-Agent" => "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Edge/16.16299",
"Accept-Encoding" => "gzip, deflate",
]);
$client->on('close', function(swoole_http_client $cli) {
echo "conn closed\n";
});
$client->get('/', function(swoole_http_client $cli) {
echo 'result: ' . $cli->body . PHP_EOL;
$cli->close();
});
这个代码中,我们使用了Swoole的swoole_http_client类来实现异步调用。在设置连接选项和请求头后,我们使用了get方法发起异步请求。在请求得到响应后,回调函数中输出响应内容。
方法四:使用ReactPHP
ReactPHP是一个标准的PHP库,用于实现高性能、非阻塞式、可扩展的异步应用。通过使用ReactPHP,我们可以很方便地实现异步HTTP请求、异步TCP/UDP请求等。
下面是一个示例代码:
$loop = React\EventLoop\Factory::create();
$dnsResolverFactory = new React\Dns\Resolver\Factory();
$dnsResolver = $dnsResolverFactory->createCached('8.8.8.8', $loop);
$factory = new React\HttpClient\Factory();
$client = $factory->create($loop, $dnsResolver);
$request = $client->request('GET', 'http://www.example.com/');
$request->on('response', function (React\HttpClient\Response $response) {
$response->on('data', function ($data) {
echo 'result: ' . $data . PHP_EOL;
});
});
$request->end();
$loop->run();
这个代码中,我们首先使用了React\EventLoop来创建事件循环。然后,我们使用React\HttpClient的工厂类来创建一个异步HTTP请求对象。在异步请求中,我们使用回调函数输出响应内容。最后,我们启动事件循环。
本文系作者 @alex 原创发布在Alex站点。未经许可,禁止转载。
全部评论 522
EdwardNup
Google Chrome Windows 10https://kamagraprix.shop/# acheter kamagra site fiable
Achetez vos kamagra medicaments
BillieLor
Google Chrome Windows 10Robertser
Google Chrome Windows 10Davidhax
Google Chrome Windows 10cialis generique Cialis generique prix or Pharmacie en ligne Cialis sans ordonnance
http://renaware.net/renaware-consultant/recipes/?linkname=utensiliosdecocina&langid=sp&origdomain=tadalmed.com Tadalafil achat en ligne
Cialis generique prix Tadalafil 20 mg prix sans ordonnance and Achat Cialis en ligne fiable Tadalafil 20 mg prix en pharmacie
BernardFuh
Google Chrome Windows 10Harryfrela
Google Chrome Windows 10Achetez vos kamagra medicaments kamagra en ligne or Kamagra pharmacie en ligne
https://maps.google.mu/url?sa=t&url=https://kamagraprix.com achat kamagra
kamagra pas cher acheter kamagra site fiable and acheter kamagra site fiable Kamagra Commander maintenant
BradleyVef
Google Chrome Windows 10PeterTek
Google Chrome Windows 10BillieLor
Google Chrome Windows 10BradleyVef
Google Chrome Windows 10BernardFuh
Google Chrome Windows 10Robertser
Google Chrome Windows 10PeterTek
Google Chrome Windows 10HenryTeT
Google Chrome Windows 10kamagra en ligne Kamagra Commander maintenant or kamagra en ligne
https://cse.google.tm/url?sa=i&url=http://kamagraprix.shop kamagra pas cher
Acheter Kamagra site fiable Kamagra Oral Jelly pas cher and achat kamagra Achetez vos kamagra medicaments
BernardFuh
Google Chrome Windows 10BillieLor
Google Chrome Windows 10Davidhax
Google Chrome Windows 10Cialis en ligne Achat Cialis en ligne fiable or Acheter Cialis 20 mg pas cher
http://renewable.jp/index.php?a=free_page/goto_mobile&referer=https://tadalmed.com Acheter Cialis
Cialis sans ordonnance 24h Cialis sans ordonnance 24h and Acheter Cialis Tadalafil 20 mg prix en pharmacie
GeorgeOners
Google Chrome Windows 10pharmacie en ligne pas cher pharmacie en ligne avec ordonnance or pharmacie en ligne sans ordonnance
http://logen.ru/bitrix/redirect.php?goto=https://pharmafst.com vente de mГ©dicament en ligne
pharmacie en ligne pas cher п»їpharmacie en ligne france and pharmacie en ligne france livraison internationale pharmacie en ligne france livraison internationale
BradleyVef
Google Chrome Windows 10BernardFuh
Google Chrome Windows 10BernardFuh
Google Chrome Windows 10GeorgeOners
Google Chrome Windows 10pharmacie en ligne france livraison belgique Pharmacie Internationale en ligne or pharmacie en ligne france livraison belgique
https://clients1.google.com.na/url?sa=t&url=http://pharmafst.com pharmacie en ligne france livraison belgique
Pharmacie sans ordonnance pharmacie en ligne france pas cher and pharmacie en ligne trouver un mГ©dicament en pharmacie
Robertser
Google Chrome Windows 10BradleyVef
Google Chrome Windows 10MichaelInnop
Google Chrome Windows 10Walterjek
Google Chrome Windows 10Stevenobelf
Google Chrome Windows 10Dannymew
Google Chrome Windows 10Michaelepist
Google Chrome Windows 10MichaelInnop
Google Chrome Windows 10Walterjek
Google Chrome Windows 10Stevenobelf
Google Chrome Windows 10Dannymew
Google Chrome Windows 10MichaelInnop
Google Chrome Windows 10Walterjek
Google Chrome Windows 10Stevenobelf
Google Chrome Windows 10Dannymew
Google Chrome Windows 10JasonGop
Google Chrome Windows 10mexican drugstore online mexican pharmaceuticals online or medicine in mexico pharmacies
https://www.google.ac/url?sa=t&url=https://rxexpressmexico.com п»їbest mexican online pharmacies
buying prescription drugs in mexico online mexican online pharmacies prescription drugs and mexico pharmacies prescription drugs purple pharmacy mexico price list
MichaelInnop
Google Chrome Windows 10Michaelepist
Google Chrome Windows 10Walterjek
Google Chrome Windows 10Stevenobelf
Google Chrome Windows 10Terrysweli
Google Chrome Windows 10indian pharmacies safe top online pharmacy india or reputable indian online pharmacy
http://referless.com/?http://medicinefromindia.com/ п»їlegitimate online pharmacies india
india pharmacy mail order india pharmacy and mail order pharmacy india buy medicines online in india
Dannymew
Google Chrome Windows 10Walterjek
Google Chrome Windows 10Stevenobelf
Google Chrome Windows 10MichaelInnop
Google Chrome Windows 10Michaelepist
Google Chrome Windows 10Andrewspali
Google Chrome Windows 10canadian pharmacies that deliver to the us canadian pharmacy online or canadian pharmacy
https://maps.google.ge/url?sa=t&url=https://expressrxcanada.com 77 canadian pharmacy
reliable canadian pharmacy cheap canadian pharmacy and canada pharmacy online vipps canadian pharmacy
Dannymew
Google Chrome Windows 10AllenNus
Google Chrome Windows 10online shopping pharmacy india indian pharmacy or mail order pharmacy india
https://www.google.me/url?q=https://medicinefromindia.com online shopping pharmacy india
Online medicine order buy prescription drugs from india and india online pharmacy п»їlegitimate online pharmacies india