diff --git a/console/controllers/AmqpController.php b/console/controllers/AmqpController.php index e7c3bc0..e06c765 100644 --- a/console/controllers/AmqpController.php +++ b/console/controllers/AmqpController.php @@ -2,19 +2,21 @@ namespace console\controllers; use Ely\Amqp\ControllerTrait; +use Exception; use PhpAmqpLib\Message\AMQPMessage; use Yii; use yii\console\Controller; use yii\db\Exception as YiiDbException; use yii\helpers\ArrayHelper; use yii\helpers\Inflector; -use yii\helpers\StringHelper; abstract class AmqpController extends Controller { use ControllerTrait { callback as _callback; } + private $reconnected = false; + public final function actionIndex() { $this->start(); } @@ -35,12 +37,17 @@ abstract class AmqpController extends Controller { try { $this->_callback($msg); } catch (YiiDbException $e) { - if (StringHelper::startsWith($e->getMessage(), 'Error while sending QUERY packet')) { - exit(self::EXIT_CODE_ERROR); + if ($this->reconnected || !$this->isRestorableException($e)) { + throw $e; } - throw $e; + $this->reconnected = true; + Yii::$app->db->close(); + Yii::$app->db->open(); + $this->callback($msg); } + + $this->reconnected = false; } /** @@ -57,4 +64,9 @@ abstract class AmqpController extends Controller { return ArrayHelper::getValue($this->getRoutesMap(), $route, 'route' . Inflector::camelize($route)); } + private function isRestorableException(Exception $e): bool { + return strpos($e->getMessage(), 'MySQL server has gone away') !== false + || strcmp($e->getMessage(), 'Error while sending QUERY packet') !== false; + } + }