ubuntu 20.04 php7.4编译安装swoole:
apt install php-cli php-dev libcurl4-openssl-dev php-curl libc-ares-dev
wget https://github.com/swoole/swoole-src/archive/v4.8.13.tar.gz
tar zxf v4.8.13.tar.gz
cd swoole-src-4.8.13
phpize
./configure --enable-openssl --enable-http2 --enable-swoole-curl --enable-cares
make && make install
echo 'extension=swoole.so' > /etc/php/7.4/cli/conf.d/20-swoole.ini
php --ri swoole
#减小swoole.so文件的大小
strip -s /usr/lib/php/20190902/swoole.so
debian12安装swoole5:
apt install php-cli php-dev libcurl4-openssl-dev php-curl libc-ares-dev libbrotli-dev
wget https://github.com/swoole/swoole-src/archive/refs/tags/v5.1.4.tar.gz
./configure --enable-openssl --enable-swoole-curl --enable-cares
swoole原生协程http客户端:
<?php
//Co::set(['hook_flags' => SWOOLE_HOOK_ALL]);
$count = 10;
Co\run(function () use (&$result, $count) {
$wg = new \Swoole\Coroutine\WaitGroup();
$result = [];
for ($i = 1; $i <= $count; $i++) {
$wg->add();
go(function () use ($i, $wg, &$result) {
$cli = new Swoole\Coroutine\Http\Client('www.baidu.com', 80);
$cli->set(['timeout' => 10]);
$cli->setHeaders([
'Host' => 'www.baidu.com',
'User-Agent' => 'Mozilla/5.0 Firefox/78.0',
]);
$cli->get('/');
$result[$i] = $cli->getStatusCode();
$cli->close();
$wg->done();
});
}
$wg->wait();
});
var_dump($result);
以hook方式协程运行php curl:
<?php
//Co::set(['hook_flags' => SWOOLE_HOOK_ALL]);
Co\run(function () {
$chan = new Swoole\Coroutine\Channel(10);
for ($i = 1; $i <= 10; $i++) {
go(function () use ($i, $chan) {
$header = array(
'User-Agent: Mozilla/5.0 Firefox/78.0'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.baidu.com");
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$chan->push(['index' => $i, 'code' => $code]);
});
}
for ($i = 1; $i <= 10; $i++) {
$res = $chan->pop();
var_dump($res);
}
});