🚀 Coroutine-based concurrency library for PHP
Run Swoole program by Docker
docker run --rm phpswoole/swoole "php --ri swoole"For details on how to use it, see: How to Use This Image.
$http = new Swoole\Http\Server('127.0.0.1', 9501);
$http->set(['hook_flags' => SWOOLE_HOOK_ALL]);
$http->on('request', function ($request, $response) {
$result = [];
Co::join([
go(function () use (&$result) {
$result['google'] = file_get_contents("https://www.google.com/");
}),
go(function () use (&$result) {
$result['taobao'] = file_get_contents("https://www.taobao.com/");
})
]);
$response->end(json_encode($result));
});
$http->start();…Swoole hooks the blocking io function of PHP at the bottom layer and automatically converts it to a non-blocking function, so that these functions can be called concurrently in coroutines.
ext-curl (Support symfony and guzzle)ext-redisext-mysqliext-pdo_mysqlext-pdo_pgsqlext-pdo_sqliteext-pdo_oracleext-pdo_odbcstream functions (e.g. stream_socket_client/stream_socket_server), Supports TCP/UDP/UDG/Unix/SSL/TLS/FileSystem API/Pipeext-socketsext-soapsleep/usleep/time_sleep_untilproc_opengethostbyname/shell_exec/execfread/fopen/fsockopen/fwrite/flockProject Awesome Swoole maintains a curated list of awesome things related to Swoole, including
The network layer in Swoole is event-based and takes full advantage of the underlying epoll/kqueue implementation, making it really easy to serve millions of requests.
Swoole 4.x uses a brand new engine kernel and now it has a full-time developer team, so we are entering an unprecedented period in PHP history which offers a unique possibility for rapid evolution in performance.
Swoole 4.x or later supports the built-in coroutine with high availability, and you can use fully synchronized code to implement asynchronous performance. PHP code without any additional keywords, the underlying automatic coroutine-scheduling.
Developers can understand coroutines as ultra-lightweight threads, and you can easily create thousands of coroutines in a single process.
Concurrency 10K requests to read data from MySQL takes only 0.2s!
…You can create multiple services on the single event loop: TCP, HTTP, Websocket and HTTP2, and easily handle thousands of requests.
function tcp_pack(string $data): string
{
return pack('N', strlen($data)) . $data;
}
function tcp_unpack(string $data): string
{
return substr($data, 4, unpack('N', substr($data, 0, 4))[1]);
}
$tcp_options = [
'open_length_check' => true,
'package_length_type' => 'N',
'package_length_offset' => 0,
'package_body_offset' => 4
];…Whether you DNS query or send requests or receive responses, all of these are scheduled by coroutine automatically.
…Channel is the only way for exchanging data between coroutines, the development combination of the Coroutine + Channel is the famous CSP programming model.
In Swoole development, Channel is usually used for implementing connection pool or scheduling coroutine concurrent.
In the following example, we have a thousand concurrently requests to redis. Normally, this has exceeded the maximum number of Redis connections setting and will throw a connection exception, but the connection pool based on Channel can perfectly schedule requests. We don't have to worry about connection overload.
…Some Swoole's clients implement the defer mode for concurrency, but you can still implement it flexible with a combination of coroutines and channels.
…$id = Swoole\Timer::tick(100, function () {
echo "⚙️ Do something...\n";
});
Swoole\Timer::after(500, function () use ($id) {
Swoole\Timer::clear($id);
echo "⏰ Done\n";
});
Swoole\Timer::after(1000, function () use ($id) {
if (!Swoole\Timer::exists($id)) {
echo "✅ All right!\n";
}
});go(function () {
$i = 0;
while (true) {
Co::sleep(0.1);
echo "📝 Do something...\n";
if (++$i === 5) {
echo "🛎 Done\n";
break;
}
}
echo "🎉 All right!\n";
});As of Swoole v4.1.0, we added the ability to transform synchronous PHP network libraries into co-routine libraries using a single line of code.
Simply call the Swoole\Runtime::enableCoroutine() method at the top of your script. In the sample below we connect to php-redis and concurrently read 10k requests in 0.1s:
Swoole\Runtime::enableCoroutine();
$s = microtime(true);
Co\run(function() {
for ($c = 100; $c--;) {
go(function () {
($redis = new Redis)->connect('127.0.0.1', 6379);
for ($n = 100; $n--;) {
assert($redis->get('awesome') === 'swoole');
}
});
}
});
echo 'use ' . (microtime(true) - $s) . ' s';By calling this method, the Swoole kernel replaces ZendVM stream function pointers. If you use php_stream based extensions, all socket operations can be dynamically converted to be asynchronous IO scheduled by coroutine at runtime!
Sleep 10K times, read, write, check and delete files 10K times, use PDO and MySQLi to communicate with the database 10K times, create a TCP server and multiple clients to communicate with each other 10K times, create a UDP server and multiple clients to communicate with each other 10K times... Everything works well in one process!
Just see what the Swoole brings, just imagine...
…As with any open source project, Swoole always provides the most reliable stability and the most powerful features in the latest released version. Please ensure as much as possible that you are using the latest version.
pecl install swoolePlease download the source packages from Releases or clone a specific version. Don't use master branch as it may be in development.
To clone the source code from git specify a tag:
git clone --branch v6.0.0 --single-branch https://github.com/swoole/swoole-src.git && \
cd swoole-srcCompile and install at the source folder:
phpize && \
./configure && \
make && make installAfter compiling and installing to the system successfully, you have to add a new line extension=swoole.so to php.ini to enable Swoole extension.
for example:
./configure --enable-openssl --enable-sockets
--enable-openssl or --with-openssl-dir=DIR--enable-sockets--enable-mysqlnd (need mysqlnd, it just for supporting $mysql->escape method)--enable-swoole-curl⚠️ If you upgrade from source, don't forget to
make cleanbefore you upgrade your swoole
pecl upgrade swoolecd swoole-src && git pull && make clean && make && sudo make installphpize clean && phpize then try to compileAsync clients and API are moved to a separate PHP extension swoole_async since version 4.3.0, install swoole_async:
git clone https://github.com/swoole/ext-async.git
cd ext-async
phpize
./configure
make -j 4
sudo make installEnable it by adding a new line extension=swoole_async.so to php.ini.
Security issues should be reported privately, via email, to the Swoole develop team [email protected]. You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message.
Your contribution to Swoole development is very welcome!
You may contribute in the following ways:
This project exists thanks to all the people who contribute. [Contributors].
Demin has been playing with PHP since 2000, focusing on building high-performance, secure web services. He is an occasional conference speaker on PHP and Swoole, and has been working for companies in the states like eBay, Visa and Glu Mobile for years. You may find Demin on Twitter or GitHub.
Apache License Version 2.0 see http://www.apache.org/licenses/LICENSE-2.0.html
6.2.3: ASAN errors
6.2.3: zts + docker + io_uring: ERROR Iouring::Iouring(): Failed to initialize io_uring instance, Error: Operation not permitted[1]
SIGTERM 平滑退出时过早移除 worker pipe 读事件,导致已提交 Task 的 onFinish 丢失
6.2.3 compile error under PHP 8.5.10
Add a Windows random source for WebSocket masking keys
Queue consumer: All coroutines are asleep - deadlock
WebSocket push coroutines remain suspended after peer close with send_yield=true (6.2.2, SWOOLE_BASE)
PHP 8.5/aarch64: coroutine VM stack use-after-free under high coroutine churn
自定义进程 信号问题