swoole一键协程化(curl函数)

2021-10-31

方法1

使用前需要在编译时开启--enable-swoole-curl 

use Swoole\Coroutine;
use function Swoole\Coroutine\run;

Coroutine::set(['hook_flags'=> SWOOLE_HOOK_NATIVE_CURL]);

run(function() {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "http://httpbin.org/get");
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $result = curl_exec($ch);
    curl_close($ch);
    var_dump($result);
});

方法2

一键协程化,包括了:curl_init,curl_setopt,curl_exec,curl_multi_getcontent,curl_setopt_array,curl_error,curl_getinfo,curl_errno,curl_close,curl_reset

use Swoole\Coroutine;
use function Swoole\Coroutine\run;

Coroutine::set(['hook_flags'=> SWOOLE_HOOK_CURL]);

run(function() {
    $ch = curl_init();  
    curl_setopt($ch, CURLOPT_URL, "http://www.xinhuanet.com/");  
    curl_setopt($ch, CURLOPT_HEADER, false);  
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $result = curl_exec($ch);  
    curl_close($ch);
    var_dump($result);
});

 

{/if}