title: SyncInvoker meta:

  • name: description content: EasySwoole provides a synchronization program coroutine call conversion driver
  • name: keywords content: swoole|swoole extension|swoole framework|easyswoole|SyncInvoker

SyncInvoker

Scenes

After Swoole 4.x, it provides a very powerful coroutine capability, which allows us to better squeeze server performance and improve concurrency. However, currently PHP is not perfect in the swoole coroutine ecosystem, such as the monogodb client without the coroutine version, and in order to avoid calling the synchronous blocking API in the worker, for example, using the synchronized mango client in the Http callback. End, causing the worker to degenerate into a synchronous blocking, resulting in no way to fully exploit the advantages of the coroutine. EasySwoole provides a synchronous program coroutine call conversion driver.

Principle

Start the custom process to listen to the UnixSocket, and then the worker side calls the coroutine client to send the command to the custom process and process it, and then the processing result is returned to the worker’s coroutine client.

Installation

  1. composer require easyswoole/sync-invoker

Use

Define a driver work instance (you can define multiple)

  1. namespace App;
  2. use EasySwoole\SyncInvoker\AbstractInvoker;
  3. use EasySwoole\SyncInvoker\SyncInvoker;
  4. use EasySwoole\Component\Singleton;
  5. class MyInvokerDriver extends AbstractInvoker{
  6. private $stdclass;
  7. function __construct()
  8. {
  9. $this->stdclass = new \stdClass();
  10. parent::__construct();
  11. }
  12. public function test($a,$b)
  13. {
  14. return $a+$b;
  15. }
  16. public function a()
  17. {
  18. return 'this is a';
  19. }
  20. public function getStdClass()
  21. {
  22. return $this->stdclass;
  23. }
  24. }
  25. //Register a corresponding caller
  26. class MyInvoker extends SyncInvoker
  27. {
  28. use Singleton;
  29. }

mainServerCreate in the EasySwoole global event is registered

  1. MyInvoker::getInstance(new MyInvokerDriver())->attachServer(ServerManager::getInstance()->getSwooleServer());

Once the service is started, it can be called from anywhere

  1. $ret = MyInvoker::getInstance()->client()->test(1,2);
  2. var_dump($ret);
  3. var_dump(MyInvoker::getInstance()->client()->a());
  4. var_dump(MyInvoker::getInstance()->client()->a(1));
  5. var_dump(MyInvoker::getInstance()->client()->fuck());
  6. $ret = MyInvoker::getInstance()->client()->callback(function (MyInvokerDriver $driver){
  7. $std = $driver->getStdClass();
  8. if(isset($std->time)){
  9. return $std->time;
  10. }else{
  11. $std->time = time();
  12. return 'new set time';
  13. }
  14. });

Precautions

  • Try to use the function name calling method, the closure mode call will have some closure function serialization failure problem
  • Pass parameters, return results as far as possible with arrays or strings, resource objects cannot be serialized