Heim  >  Artikel  >  Backend-Entwicklung  >  PHP如何请求url之后不需要等待url返回值,直接执行后面代码?

PHP如何请求url之后不需要等待url返回值,直接执行后面代码?

WBOY
WBOYOriginal
2016-06-06 20:24:241565Durchsuche

最近开发中遇到这么一个问题,程序第4行会请求一个url,但是这个url的响应时间很长,而且我的程序中用不到他的返回值,所以我在想能不能在第4行发送请求之后不用等待他返回值,直接执行第5行代码,可以吗?如果可以的话,怎么做到?

回复内容:

最近开发中遇到这么一个问题,程序第4行会请求一个url,但是这个url的响应时间很长,而且我的程序中用不到他的返回值,所以我在想能不能在第4行发送请求之后不用等待他返回值,直接执行第5行代码,可以吗?如果可以的话,怎么做到?

http://www.laruence.com/2008/04/14/318.html

sleep(10)这个长达10秒的操作由正在提供Web服务的PHP进程来处理显然是不合适的,因为这肯定会造成一个PHP工作进程被阻塞.这时可以考虑用popen或proc_open异步调用一个CLI程序进行一些耗时的操作.

<code>/www/index.php
<?php $sec = 10;
//pclose(popen('/www/cli.php '.$sec.' &', 'r'));
pclose(popen("/www/cli.php -s $sec &", 'r'));

/www/cli.php
#!/png/php/5.4.39NTS/bin/php
<?php
$argv = getopt('s:');
sleep($argv['s']);
file_put_contents('/www/cli.txt', $argv['s']);
//print_r($argv);
//cli.php处理完耗时的任务后往数据库存结果,浏览器端用AJAX轮询异步得到数据.</code></code>

如果你用不到这个返回,你可以直接把这个地址存到数据库,由别的程序在服务器上执行

要是用php-fpm可以看看这个函数fastcgi_finish_request
你把运行慢的代码写在这个函数之后就可以了
http://php.net/manual/zh/function.fastcgi-finish-request.php

可以使用 php 异步扩展 swoole.

  1. 可以用多线程,pthread扩展,http://php.net/manual/en/book.pthreads.php

  2. 把请求操作放在队列中,异步执行

<code><?php $context = stream_context_create(array(
     'http' => array(
      'timeout' => 5
     ) 
));  

$contents = file_get_contents('http://www.google.com', 0, $context);

echo '5秒后到这'
?></code>

用队列请求
用队列请求
用队列请求

这肯定是不可以的 !

要么你使用队列执行 .
要么 你用 swoole 或者 Node.js

PHP 在设计上就决定了 , 它只能从头到尾执行 。

生产者/消费者模式

简单粗暴的写法,可以把这个逻辑用register_shutdown_function()执行

你不需要返回一个请求的内容 你去请求他干啥。。。

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn