2016-04-12 03:16:44 +05:30
|
|
|
|
<?php
|
2016-11-16 01:15:30 +05:30
|
|
|
|
namespace console\controllers;
|
2016-04-12 03:16:44 +05:30
|
|
|
|
|
2016-08-16 03:57:18 +05:30
|
|
|
|
use Ely\Amqp\ControllerTrait;
|
2017-11-04 18:22:57 +05:30
|
|
|
|
use Exception;
|
2016-12-24 04:14:31 +05:30
|
|
|
|
use PhpAmqpLib\Message\AMQPMessage;
|
2016-08-16 03:57:18 +05:30
|
|
|
|
use Yii;
|
|
|
|
|
use yii\console\Controller;
|
2016-12-24 04:14:31 +05:30
|
|
|
|
use yii\db\Exception as YiiDbException;
|
2016-08-16 03:57:18 +05:30
|
|
|
|
use yii\helpers\ArrayHelper;
|
|
|
|
|
use yii\helpers\Inflector;
|
2016-04-12 03:16:44 +05:30
|
|
|
|
|
|
|
|
|
abstract class AmqpController extends Controller {
|
2016-12-24 04:14:31 +05:30
|
|
|
|
use ControllerTrait {
|
|
|
|
|
callback as _callback;
|
|
|
|
|
}
|
2016-08-16 03:57:18 +05:30
|
|
|
|
|
2017-11-04 18:22:57 +05:30
|
|
|
|
private $reconnected = false;
|
|
|
|
|
|
2018-04-18 02:17:25 +05:30
|
|
|
|
final public function actionIndex() {
|
2016-08-16 03:57:18 +05:30
|
|
|
|
$this->start();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public function getRoutesMap() {
|
|
|
|
|
return [];
|
|
|
|
|
}
|
|
|
|
|
|
2016-12-24 04:14:31 +05:30
|
|
|
|
/**
|
|
|
|
|
* Переопределяем метод callback, чтобы избержать логгирования в консоль ошибок,
|
|
|
|
|
* связанных с обвалом того или иного соединения. Это нормально, PHP рождён умирать,
|
|
|
|
|
* а не работать 24/7 в качестве демона.
|
|
|
|
|
*
|
|
|
|
|
* @param AMQPMessage $msg
|
|
|
|
|
* @throws YiiDbException
|
|
|
|
|
*/
|
|
|
|
|
public function callback(AMQPMessage $msg) {
|
|
|
|
|
try {
|
|
|
|
|
$this->_callback($msg);
|
|
|
|
|
} catch (YiiDbException $e) {
|
2017-11-04 18:22:57 +05:30
|
|
|
|
if ($this->reconnected || !$this->isRestorableException($e)) {
|
|
|
|
|
throw $e;
|
2016-12-24 04:14:31 +05:30
|
|
|
|
}
|
|
|
|
|
|
2017-11-04 18:22:57 +05:30
|
|
|
|
$this->reconnected = true;
|
|
|
|
|
Yii::$app->db->close();
|
|
|
|
|
Yii::$app->db->open();
|
|
|
|
|
$this->callback($msg);
|
2016-12-24 04:14:31 +05:30
|
|
|
|
}
|
2017-11-04 18:22:57 +05:30
|
|
|
|
|
|
|
|
|
$this->reconnected = false;
|
2016-12-24 04:14:31 +05:30
|
|
|
|
}
|
|
|
|
|
|
2016-08-16 03:57:18 +05:30
|
|
|
|
/**
|
|
|
|
|
* @inheritdoc
|
|
|
|
|
*/
|
|
|
|
|
protected function getConnection() {
|
|
|
|
|
return Yii::$app->amqp->getConnection();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* @inheritdoc
|
|
|
|
|
*/
|
|
|
|
|
protected function buildRouteActionName($route) {
|
|
|
|
|
return ArrayHelper::getValue($this->getRoutesMap(), $route, 'route' . Inflector::camelize($route));
|
|
|
|
|
}
|
2016-04-12 03:16:44 +05:30
|
|
|
|
|
2017-11-04 18:22:57 +05:30
|
|
|
|
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;
|
|
|
|
|
}
|
|
|
|
|
|
2016-04-12 03:16:44 +05:30
|
|
|
|
}
|