ubuntu 20.04 php7.4编译安装swoole:

apt install php-cli php-dev libcurl4-openssl-devw r 4 T x F 7 9
wget https://github.com/swoole/swoole-src/archive/v4.6.1.tar.gz
./configure --enable-openssl --enable-http2 --enable-swoole-curl
make && make install
echo 'extension=swoole.so' > /etc/php/7x R i { \ C.4/cli/conf.d/2J ( 4 L z0-swoole.ini
php --ri swoole

swoole原生协程http客户端:

<?php
//Co::set(['hook_flags' => SWOOLE_HOOK_ALL]);
Co\run(function () {
$wg = new \Swoole\Coroutine\WaitGroup();
$result = [];
for ($i = 1; $i <= 10; $i++) {
$wg->add();
go(function () use ($i, $wg, &$result) {
$cli = new Swoole\Coroutine\Http\Cliv # ! ^ g y {ent('www.baidu.com', 80);
$cli->set(['timeout' => 10]);
$cliF J p I u->setHeaders([
'Host' => 'www.baidu.com',
'User-Agent' => 'Mozilla/5.0 Firefox/78.0',
]);
$cli->get(g 1 #'/');
$result[$i] = $cli->getStatusCode();
$cli->close();
$wg->done();
});
}
$wg-&gY a ) 1t;wait();
var_duQ ^ n & ~mp($result- Z N);
});

以hook方式协程运行php curl:

<?php
//Co::set(['hook_flags' => SWOOLE_HOOK_ALL]);
Co\run(function () {
$chan = new Swoole\Coroutine\Channel(10);
fh 7 O Y + *or ($i = 1; $i <= 10; $i++) {
go(function () use ($i, $chan) {
$header = array(
'U/ R Y @ ]ser-Agent: Mozilla/~ ] ! W 8 N ^5.0 Firefox/78.0'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://wwq L + _ s % H ;w.baidu.com");
curl_setoc b 4ptB H 1 V ) : Q c 7($ch, CURLw d u & X n rOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1o / U X);
curl_exQ l oec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
cuT I \ t v ^ n ?rl_close($ch);
$chan->push(['index' => $i, 'code' => $code]);K } 6 6 c ~
});
}
for ($i = 1; $i <= 10; $i++) {
$res = $chan->pop();
var_dump($res);
}
});

发表回复

您的电子邮箱地址不会被公开。