easyswoole / sync-invoker
高效的 swoole 框架
2.1.0
2023-01-10 07:33 UTC
Requires
- php: >=8.0
- ext-swoole: ^4.4.5
- easyswoole/component: ^2.0
Requires (Dev)
README
场景
自 Swoole 4.x 版本以来,它提供了非常强大的协程能力,使我们能够更好地挖掘服务器性能,提高并发。然而,目前 PHP 在 Swoole 协程生态系统中并不完善,例如没有协程版本的 MongoDB 客户端。为了避免在 worker 中调用同步阻塞的 API,例如在 HTTP 回调中使用同步的 Mango 客户端,导致 worker 退化为同步阻塞,无法充分发挥协程的优势,EasySwoole 提供了一个同步程序协程调用转换驱动。
原理
启动自定义进程监听 UnixSocket,然后 worker 端调用协程客户端发送命令到自定义进程并处理,然后将处理结果返回给 worker 的协程客户端。
示例代码
use EasySwoole\SyncInvoker\AbstractDriver; use EasySwoole\SyncInvoker\SyncInvoker; use EasySwoole\SyncInvoker\Worker; require 'vendor/autoload.php'; class Driver extends AbstractDriver { function plus($a,$b) { $this->response($a + $b); } protected function actionNotFound() { $this->response($this->getRequest()->getAction().' not found'); } } $invoker = new SyncInvoker(); $invoker->getConfig()->setDriver(new Driver()); $invoker->getConfig()->setOnWorkerStart(function (Worker $worker){ var_dump('worker start at Id '.$worker->getArg()['workerIndex']); }); $http = new swoole_http_server("0.0.0.0", 9501); $invoker->attachServer($http); $http->on("request", function ($request, $response)use($invoker) { $ret = $invoker->invoke()->plus(1,2); var_dump($ret); $ret = $invoker->invoke()->plus2(1,2); var_dump($ret); }); $http->start();