The official version of Swoole 2.0 is released. The biggest update in version 2.0 is the addition of support for coroutines. The official version supports both PHP5 and PHP7.
Based on the Swoole2.0 coroutine, PHP developers can write code in a synchronous manner, and the bottom layer automatically schedules the coroutine and transforms it into asynchronous IO.
Solve the problem of nested callbacks in traditional asynchronous programming. (Recommended learning: swoole video tutorial)
Compared with the implementation of yield/generator and async/await in Node.js (ES6), Python and other languages, Swoole coroutine does not need to be modified. The code adds additional keywords.
Compared with goroutine in Go language, Swoole coroutine is built-in. The application layer code does not need to add the go keyword to start the coroutine. It only needs to use the encapsulated coroutine client, which is simpler to use. . In addition, the IO component of the Swoole coroutine has a built-in timeout mechanism at the bottom layer, so there is no need to use complex select/chan/timer to implement client timeout.
Currently, the built-in coroutine client components at the bottom of Swoole include: udpclient, tcpclient, httpclient, redisclient, and mysqlclient, which basically cover several communication protocols commonly used by developers. Coroutine components can only be used in the server's onConnect, onRequest, onReceive, and onMessage callback functions.
Using swole coroutine
How to use coroutine:
Use go()( \Swoole\Coroutine::abbreviation of create()) Create a coroutine
In the callback function of go(), add the code that the coroutine needs to execute. Note that it is non-blocking code
use Swoole\Coroutine as Co; // 常用的缩写方式 go(function () { // 创建协程, 回调函数中写需要在协程中执行的代码 echo "daydaygo"; Co::sleep(1); // 不能是阻塞代码 });
Coroutine
As mentioned above, use go() to create a coroutine
In the swoole server, the bottom layer is automatically Automatically create a coroutine before onRequet, onReceive, onConnect and other event callbacks
The scope of influence after turning on the enable_coroutine parameter: It also mainly includes the Timer timer
The coroutine version of the Task process opened using task_enable_coroutine, A coroutine will be automatically created before the onTask callback
The process and process pool support enabling the coroutine, and the child process created after it is enabled will automatically create the coroutine
// tcp/udp server, 可以在此基础可封装 rpc $s = new \Swoole\Server(); // http server, 替代传统的 fpm $s = new \Swoole\Http\Server(); // 开启 http2 支持: https://wiki.swoole.com/wiki/page/326.html $s = new \Swoole\Http\Server(); $s->set([ 'open_http2_protocol' => true, ]); // 进而可以实现基于 http2 的服务, 比如 grpc // websocket server $s = new \Swoole\WebSocket\Server();
The above is the detailed content of How to enable swoole coroutine. For more information, please follow other related articles on the PHP Chinese website!