1:先创建服务端文件MySql.php再创建数据库以及简单的数据表
<?php use Swoole\Runtime; use Swoole\Coroutine; use function Swoole\Coroutine\run; class MySql { public function go(){ Runtime::enableCoroutine(); $s = microtime(true); Co\run(function() { for ($c = 50; $c--;) { go(function(){ $pdo = new PDO('mysql:host=127.0.0.1;dbname=demo;charset=utf8', 'demo', 'demo'); $statement = $pdo->prepare('SELECT `demo` FROM `demo` where id = 1'); for ($n = 100; $n--;) { $statement->execute(); $res = $statement -> fetch(); var_dump('a:' . $res['user_name']); } }); } for ($c = 50; $c--;) { go(function(){ $pdo = new PDO('mysql:host=127.0.0.1;dbname=demo;charset=utf8', 'demo', 'demo'); $statement = $pdo->prepare('SELECT `demo` FROM `demo` where id = 1'); for ($n = 100; $n--;) { $statement->execute(); $res = $statement -> fetch(); var_dump('b:' . $res['user_name']); } }); } }); var_dump('用时:' . (microtime(true) - $s) . ' s'); } } $mysql = new MySql(); $mysql->go();
2:启动服务php MySql.php 会发现输出的a里面掺杂b,b里面掺杂1,耗时短