From 976427c8ee80334af8f926b89e2e8cf3701a0a3a Mon Sep 17 00:00:00 2001 From: stelin <794774870@qq.com> Date: Thu, 23 May 2019 17:54:58 +0800 Subject: [PATCH 1/2] Fix worker stop and error close connection bug --- src/Connection/Connection.php | 14 ++++++ src/Listener/WorkerStopAndErrorListener.php | 53 +++++++++++++++++++++ 2 files changed, 67 insertions(+) create mode 100644 src/Listener/WorkerStopAndErrorListener.php diff --git a/src/Connection/Connection.php b/src/Connection/Connection.php index 2d4f532..6f3465d 100644 --- a/src/Connection/Connection.php +++ b/src/Connection/Connection.php @@ -177,6 +177,20 @@ public function create(): void $this->createReadPdo(); } + /** + * Close connection + */ + public function close(): void + { + if(!empty($this->pdo)){ + $this->pdo = null; + } + + if(!empty($this->readPdo)){ + $this->readPdo = null; + } + } + /** * Reconnect */ diff --git a/src/Listener/WorkerStopAndErrorListener.php b/src/Listener/WorkerStopAndErrorListener.php new file mode 100644 index 0000000..f25dab0 --- /dev/null +++ b/src/Listener/WorkerStopAndErrorListener.php @@ -0,0 +1,53 @@ + 'handle', + SwooleEvent::WORKER_ERROR => 'handle', + ]; + } + + /** + * @param EventInterface $event + */ + public function handle(EventInterface $event): void + { + go(function () use ($event){ + $pools = BeanFactory::getBeans(Pool::class); + + /* @var Pool $pool */ + foreach ($pools as $pool) { + $count = $pool->close(); + + CLog::info('Close %d database connection on %s!', $count, $event->getName()); + } + }); + + Event::wait(); + } +} \ No newline at end of file From 475b534e34caa865a139b98160d5206ea2940f8b Mon Sep 17 00:00:00 2001 From: stelin <794774870@qq.com> Date: Thu, 23 May 2019 19:52:32 +0800 Subject: [PATCH 2/2] Modify event name add --- src/Listener/WorkerStopAndErrorListener.php | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/Listener/WorkerStopAndErrorListener.php b/src/Listener/WorkerStopAndErrorListener.php index f25dab0..a434470 100644 --- a/src/Listener/WorkerStopAndErrorListener.php +++ b/src/Listener/WorkerStopAndErrorListener.php @@ -10,6 +10,7 @@ use Swoft\Event\EventSubscriberInterface; use Swoft\Log\Helper\CLog; use Swoft\Server\Swoole\SwooleEvent; +use Swoft\SwoftEvent; use Swoole\Event; /** @@ -27,8 +28,8 @@ class WorkerStopAndErrorListener implements EventSubscriberInterface public static function getSubscribedEvents(): array { return [ - SwooleEvent::WORKER_STOP => 'handle', - SwooleEvent::WORKER_ERROR => 'handle', + SwooleEvent::WORKER_STOP => 'handle', + SwoftEvent::WORKER_SHUTDOWN => 'handle', ]; }