[关闭]
@Chiang 2020-01-06T17:48:09.000000Z 字数 5283 阅读 556

Swoole 理解一

Swoole


网络通信引擎

常驻进程
swoole 扩展了生命周期

基于事件的高性能异步

协程

协程 线程 进程 区别

mysql 客户端

并发1万个请求从MySQL读取海量数据仅需要0.2秒

  1. $s = microtime(true);
  2. Co\run(function() {
  3. for ($c = 100; $c--;) {
  4. go(function () {
  5. $mysql = new Swoole\Coroutine\MySQL;
  6. $mysql->connect([
  7. 'host' => '127.0.0.1',
  8. 'user' => 'root',
  9. 'password' => 'root',
  10. 'database' => 'test'
  11. ]);
  12. $statement = $mysql->prepare('SELECT * FROM `user`');
  13. for ($n = 100; $n--;) {
  14. $result = $statement->execute();
  15. assert(count($result) > 0);
  16. }
  17. });
  18. }
  19. });
  20. echo 'use ' . (microtime(true) - $s) . ' s';

混合服务器

你可以在一个事件循环上创建多个服务:TCP,HTTP,Websocket和HTTP2,并且能轻松承载上万请求。

  1. function tcp_pack(string $data): string
  2. {
  3. return pack('N', strlen($data)) . $data;
  4. }
  5. function tcp_unpack(string $data): string
  6. {
  7. return substr($data, 4, unpack('N', substr($data, 0, 4))[1]);
  8. }
  9. $tcp_options = [
  10. 'open_length_check' => true,
  11. 'package_length_type' => 'N',
  12. 'package_length_offset' => 0,
  13. 'package_body_offset' => 4
  14. ];
  1. $server = new Swoole\WebSocket\Server('127.0.0.1', 9501, SWOOLE_BASE);
  2. $server->set(['open_http2_protocol' => true]);
  3. // http && http2
  4. $server->on('request', function (Swoole\Http\Request $request, Swoole\Http\Response $response) {
  5. $response->end('Hello ' . $request->rawcontent());
  6. });
  7. // websocket
  8. $server->on('message', function (Swoole\WebSocket\Server $server, Swoole\WebSocket\Frame $frame) {
  9. $server->push($frame->fd, 'Hello ' . $frame->data);
  10. });
  11. // tcp
  12. $tcp_server = $server->listen('127.0.0.1', 9502, SWOOLE_TCP);
  13. $tcp_server->set($tcp_options);
  14. $tcp_server->on('receive', function (Swoole\Server $server, int $fd, int $reactor_id, string $data) {
  15. $server->send($fd, tcp_pack('Hello ' . tcp_unpack($data)));
  16. });
  17. $server->start();

多种客户端

不管是DNS查询抑或是发送请求和接收响应,都是协程调度的,不会产生任何阻塞。

  1. go(function () {
  2. // http
  3. $http_client = new Swoole\Coroutine\Http\Client('127.0.0.1', 9501);
  4. assert($http_client->post('/', 'Swoole Http'));
  5. var_dump($http_client->body);
  6. // websocket
  7. $http_client->upgrade('/');
  8. $http_client->push('Swoole Websocket');
  9. var_dump($http_client->recv()->data);
  10. });
  11. go(function () {
  12. // http2
  13. $http2_client = new Swoole\Coroutine\Http2\Client('localhost', 9501);
  14. $http2_client->connect();
  15. $http2_request = new Swoole\Http2\Request;
  16. $http2_request->method = 'POST';
  17. $http2_request->data = 'Swoole Http2';
  18. $http2_client->send($http2_request);
  19. $http2_response = $http2_client->recv();
  20. var_dump($http2_response->data);
  21. });
  22. go(function () use ($tcp_options) {
  23. // tcp
  24. $tcp_client = new Swoole\Coroutine\Client(SWOOLE_TCP);
  25. $tcp_client->set($tcp_options);
  26. $tcp_client->connect('127.0.0.1', 9502);
  27. $tcp_client->send(tcp_pack('Swoole Tcp'));
  28. var_dump(tcp_unpack($tcp_client->recv()));
  29. });

通道

通道(Channel)是协程之间通信交换数据的唯一渠道, 而协程+通道的开发组合即为著名的CSP编程模型
在Swoole开发中,Channel常用于连接池的实现和协程并发的调度。

连接池最简示例

在以下示例中,我们并发了一千个redis请求,通常的情况下,这已经超过了Redis最大的连接数,将会抛出连接异常, 但基于Channel实现的连接池可以完美地调度请求,开发者就无需担心连接过载。

  1. class RedisPool
  2. {
  3. /**@var \Swoole\Coroutine\Channel */
  4. protected $pool;
  5. /**
  6. * RedisPool constructor.
  7. * @param int $size max connections
  8. */
  9. public function __construct(int $size = 100)
  10. {
  11. $this->pool = new \Swoole\Coroutine\Channel($size);
  12. for ($i = 0; $i < $size; $i++) {
  13. $redis = new \Swoole\Coroutine\Redis();
  14. $res = $redis->connect('127.0.0.1', 6379);
  15. if ($res == false) {
  16. throw new \RuntimeException("failed to connect redis server.");
  17. } else {
  18. $this->put($redis);
  19. }
  20. }
  21. }
  22. public function get(): \Swoole\Coroutine\Redis
  23. {
  24. return $this->pool->pop();
  25. }
  26. public function put(\Swoole\Coroutine\Redis $redis)
  27. {
  28. $this->pool->push($redis);
  29. }
  30. public function close(): void
  31. {
  32. $this->pool->close();
  33. $this->pool = null;
  34. }
  35. }
  36. go(function () {
  37. $pool = new RedisPool();
  38. // max concurrency num is more than max connections
  39. // but it's no problem, channel will help you with scheduling
  40. for ($c = 0; $c < 1000; $c++) {
  41. go(function () use ($pool, $c) {
  42. for ($n = 0; $n < 100; $n++) {
  43. $redis = $pool->get();
  44. assert($redis->set("awesome-{$c}-{$n}", 'swoole'));
  45. assert($redis->get("awesome-{$c}-{$n}") === 'swoole');
  46. assert($redis->delete("awesome-{$c}-{$n}"));
  47. $pool->put($redis);
  48. }
  49. });
  50. }
  51. });

生产和消费

Swoole的部分客户端实现了defer机制来进行并发,但你依然可以用协程和通道的组合来灵活地实现它。

  1. go(function () {
  2. // User: I need you to bring me some information back.
  3. // Channel: OK! I will be responsible for scheduling.
  4. $channel = new Swoole\Coroutine\Channel;
  5. go(function () use ($channel) {
  6. // Coroutine A: Ok! I will show you the github addr info
  7. $addr_info = Co::getaddrinfo('github.com');
  8. $channel->push(['A', json_encode($addr_info, JSON_PRETTY_PRINT)]);
  9. });
  10. go(function () use ($channel) {
  11. // Coroutine B: Ok! I will show you what your code look like
  12. $mirror = Co::readFile(__FILE__);
  13. $channel->push(['B', $mirror]);
  14. });
  15. go(function () use ($channel) {
  16. // Coroutine C: Ok! I will show you the date
  17. $channel->push(['C', date(DATE_W3C)]);
  18. });
  19. for ($i = 3; $i--;) {
  20. list($id, $data) = $channel->pop();
  21. echo "From {$id}:\n {$data}\n";
  22. }
  23. // User: Amazing, I got every information at earliest time!
  24. });

定时器

  1. $id = Swoole\Timer::tick(100, function () {
  2. echo "⚙ Do something...\n";
  3. });
  4. Swoole\Timer::after(500, function () use ($id) {
  5. Swoole\Timer::clear($id);
  6. echo "⏰ Done\n";
  7. });
  8. Swoole\Timer::after(1000, function () use ($id) {
  9. if (!Swoole\Timer::exists($id)) {
  10. echo "✅ All right!\n";
  11. }
  12. });

使用协程方法

  1. go(function () {
  2. $i = 0;
  3. while (true) {
  4. Co::sleep(0.1);
  5. echo "📝 Do something...\n";
  6. if (++$i === 5) {
  7. echo "🛎 Done\n";
  8. break;
  9. }
  10. }
  11. echo "🎉 All right!\n";
  12. });

强大的运行时钩子

在最新版本的Swoole中,我们添加了一项新功能,使PHP原生的同步网络库一键化成为协程库。
只需在脚本顶部调用Swoole\Runtime::enableCoroutine()方法并使用php-redis,并发1万个请求从Redis读取数据仅需0.1秒!

  1. Swoole\Runtime::enableCoroutine();
  2. $s = microtime(true);
  3. Co\run(function() {
  4. for ($c = 100; $c--;) {
  5. go(function () {
  6. ($redis = new Redis)->connect('127.0.0.1', 6379);
  7. for ($n = 100; $n--;) {
  8. assert($redis->get('awesome') === 'swoole');
  9. }
  10. });
  11. }
  12. });
  13. echo 'use ' . (microtime(true) - $s) . ' s';

调用它之后,Swoole内核将替换ZendVM中的Stream函数指针,如果使用基于php_stream的扩展,则所有套接字操作都可以在运行时动态转换为协程调度的异步IO。


参考资料:
swoole微课程
twosee.cn
github

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注