InteractsWithPools.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. namespace think\swoole\concerns;
  3. use Exception;
  4. use Smf\ConnectionPool\ConnectionPool;
  5. use Smf\ConnectionPool\Connectors\ConnectorInterface;
  6. use Swoole\Server;
  7. use think\App;
  8. use think\helper\Arr;
  9. use think\swoole\Pool;
  10. use Throwable;
  11. /**
  12. * Trait InteractsWithRpc
  13. * @package think\swoole\concerns
  14. * @property App $app
  15. * @method Server getServer()
  16. */
  17. trait InteractsWithPools
  18. {
  19. /**
  20. * @return Pool
  21. */
  22. public function getPools()
  23. {
  24. return $this->app->make(Pool::class);
  25. }
  26. protected function preparePools()
  27. {
  28. $createPools = function () {
  29. /** @var Pool $pool */
  30. $pools = $this->getPools();
  31. foreach ($this->getConfig('pool', []) as $name => $config) {
  32. $type = Arr::pull($config, 'type');
  33. if ($type && is_subclass_of($type, ConnectorInterface::class)) {
  34. $pool = new ConnectionPool(
  35. Pool::pullPoolConfig($config),
  36. $this->app->make($type),
  37. $config
  38. );
  39. $pools->add($name, $pool);
  40. //注入到app
  41. $this->app->instance("swoole.pool.{$name}", $pool);
  42. }
  43. }
  44. };
  45. $closePools = function () {
  46. try {
  47. $this->getPools()->closeAll();
  48. } catch (Exception | Throwable $e) {
  49. }
  50. };
  51. $this->onEvent('workerStart', $createPools);
  52. $this->onEvent('workerStop', $closePools);
  53. $this->onEvent('workerError', $closePools);
  54. $this->onEvent('workerExit', $closePools);
  55. }
  56. }