diff --git a/AmqpHelper.php b/AmqpHelper.php index b931e72..737d2a7 100644 --- a/AmqpHelper.php +++ b/AmqpHelper.php @@ -8,12 +8,10 @@ use dominion\amqp\AmqpLoger; class AmqpHelper { - protected static $connection; - protected static $channel; - protected static $exchange; - protected static $arQueue; + protected static $connection = []; + protected static $channel = []; + protected static $arQueue = []; protected static $prefetchCount = 1; - protected $project; public function setPrefetchCount(int $count) @@ -21,23 +19,44 @@ class AmqpHelper self::$prefetchCount = $count; } + public static function resetCache() + { + foreach (self::$connection as $conn) + { + if ($conn instanceof \AMQPConnection) + { + try + { + $conn->disconnect(); + } catch (\Throwable $e) + { + + } + } + } + self::$channel = []; + self::$arQueue = []; + self::$connection = []; + } + public function getController($queue) { $key = json_encode($queue); - if (!isset(self::$connection[$key])) + if (!isset(self::$connection[$key]) || !self::$connection[$key]->isConnected()) { - $credentials = ['heartbeat' => $queue['heartbeat']] ; - self::$connection[$key] = new \AMQPConnection($credentials); + self::$connection[$key] = new \AMQPConnection(['heartbeat' => $queue['heartbeat']]); self::$connection[$key]->setLogin(Yii::$app->params['amqp']['login']); - self::$connection[$key]->setPassword(Yii::$app->params['amqp']["pass"]); - self::$connection[$key]->setHost(Yii::$app->params['amqp']["serverName"]); - self::$connection[$key]->setPort(Yii::$app->params['amqp']["port"]); - self::$connection[$key]->setVhost(Yii::$app->params['amqp']["vhostName"]); + self::$connection[$key]->setPassword(Yii::$app->params['amqp']['pass']); + self::$connection[$key]->setHost(Yii::$app->params['amqp']['serverName']); + self::$connection[$key]->setPort(Yii::$app->params['amqp']['port']); + self::$connection[$key]->setVhost(Yii::$app->params['amqp']['vhostName']); + try { self::$connection[$key]->connect(); } catch (\AMQPConnectionException $exception) { + unset(self::$connection[$key]); AmqpLoger::log('error', $exception->getCode() . ' ' . $exception->getMessage(), 'system'); throw $exception; } @@ -48,7 +67,7 @@ class AmqpHelper public function getChannel($queue) { $key = json_encode($queue); - if (!isset(self::$channel[$key])) + if (!isset(self::$channel[$key]) || !self::$channel[$key]->isConnected()) { try { @@ -56,6 +75,7 @@ class AmqpHelper self::$channel[$key]->setPrefetchCount(self::$prefetchCount); } catch (\AMQPConnectionException $exception) { + unset(self::$channel[$key]); AmqpLoger::log('error', $exception->getCode() . ' ' . $exception->getMessage(), 'system'); throw $exception; } @@ -66,35 +86,34 @@ class AmqpHelper public function getExchange($queue) { $project = $this->getProject(); - $key = $project['name'].'_'.$project['type'].'_'.$project['flags']; - if (!isset(self::$exchange[$key])) + + try { - try - { - self::$exchange[$key] = new \AMQPExchange($this->getChannel($queue)); - self::$exchange[$key]->setName($project['name']); - self::$exchange[$key]->setType($project['type']); - self::$exchange[$key]->setFlags($project['flags']); - self::$exchange[$key]->declareExchange(); - } catch (\AMQPConnectionException | \AMQPChannelException | \AMQPExchangeException $exception) - { - AmqpLoger::log('error', $exception->getCode() . ' ' . $exception->getMessage(), 'system'); - throw $exception; - } + $exchange = new \AMQPExchange($this->getChannel($queue)); + $exchange->setName($project['name']); + $exchange->setType($project['type']); + $exchange->setFlags($project['flags']); + $exchange->declareExchange(); + return $exchange; + } catch (\AMQPConnectionException | \AMQPChannelException | \AMQPExchangeException $exception) + { + AmqpLoger::log('error', $exception->getCode() . ' ' . $exception->getMessage(), 'system'); + throw $exception; } - return self::$exchange[$key]; } public function getQueue($routeKey) { $queue = $this->getQueueConfig($routeKey); - if (isset($queue['queue']) && $queue['queue'] === false) { + if (isset($queue['queue']) && $queue['queue'] === false) + { $error = 'Конфигурация ' . $routeKey . ' предназначена только для публикации и не имеет физической очереди.'; AmqpLoger::log('error', $error, 'system'); throw new \Exception($error); } + $queueName = $queue['name']; - if(!isset(self::$arQueue[$queueName])) + if (!isset(self::$arQueue[$queueName]) || !self::$arQueue[$queueName]->getChannel()->isConnected()) { try { @@ -103,12 +122,14 @@ class AmqpHelper self::$arQueue[$queueName]->setFlags($queue['flags']); self::$arQueue[$queueName]->declareQueue(); + $exchangeName = $this->getExchange($queue)->getName(); foreach ($queue['routing'] as $routing) { - self::$arQueue[$queueName]->bind($this->getExchange($queue)->getName(), $routing); + self::$arQueue[$queueName]->bind($exchangeName, $routing); } } catch (\AMQPChannelException | \AMQPConnectionException | \AMQPQueueException $exception) { + unset(self::$arQueue[$queueName]); AmqpLoger::log('error', $exception->getCode() . ' ' . $exception->getMessage(), 'system'); throw $exception; } @@ -126,35 +147,35 @@ class AmqpHelper { $project = $this->getProject(); $queue = $project['queues'][$routeKey] ?? []; + if (empty($queue)) { - $error = 'Ключ маршрутизации '.$routeKey.' не найден'; + $error = 'Ключ маршрутизации ' . $routeKey . ' не найден'; AmqpLoger::log('error', $error, 'system'); throw new \Exception($error); } - elseif(!isset($queue["name"], $queue["routing"], $queue["flags"], $queue["heartbeat"])) + + if (!isset($queue['name'], $queue['routing'], $queue['flags'], $queue['heartbeat'])) { - $error = 'Не верный формат '.$routeKey; + $error = 'Не верный формат ' . $routeKey; AmqpLoger::log('error', $error, 'system'); throw new \Exception($error); } - else - { - return $queue; - } + + return $queue; } public function setProject($projectName) { - $projects = isset(Yii::$app->params['amqp'], Yii::$app->params['amqp']['projects']) ? Yii::$app->params['amqp']['projects'] : []; - $this->project = isset($projects[$projectName]) ? $projects[$projectName] : []; - if(empty($this->project)) + $this->project = Yii::$app->params['amqp']['projects'][$projectName] ?? []; + if (empty($this->project)) { - $error = 'проект '.$projectName.' не найден'; + $error = 'проект ' . $projectName . ' не найден'; AmqpLoger::log('error', $error, 'system'); throw new \Exception($error); } - foreach ($this->project["queues"] as $key =>$value) + + foreach ($this->project['queues'] as $key => $value) { if (isset($value['queue']) && $value['queue'] === false) { @@ -166,7 +187,7 @@ class AmqpHelper public function getProject() { - if(!isset($this->project["name"], $this->project["type"], $this->project["flags"], $this->project["queues"])) + if (!isset($this->project['name'], $this->project['type'], $this->project['flags'], $this->project['queues'])) { $error = 'не верный формат проекта очереди'; AmqpLoger::log('error', $error, 'system'); @@ -177,16 +198,14 @@ class AmqpHelper public function getQueueObject($queueName) { - if(!$this->getQueue($queueName)) + $queue = $this->getQueue($queueName); + if (!$queue) { $error = 'Очередь ' . $queueName . ' не найдена'; AmqpLoger::log('error', $error, 'system'); throw new \Exception($error); } - else - { - return $this->getQueue($queueName); - } + return $queue; } public function ack($queue, $envelope) @@ -194,11 +213,10 @@ class AmqpHelper try { $queue->ack($envelope->getDeliveryTag()); - } - catch (\Exception $exception) + } catch (\Exception $exception) { AmqpLoger::log('error', $exception->getCode() . ' ' . $exception->getMessage(), 'system'); - throw new \Exception($exception->getCode() . ' ' . $exception->getMessage()); + throw new \Exception($exception->getCode() . ' ' . $exception->getMessage(), 0, $exception); } } @@ -212,27 +230,35 @@ class AmqpHelper */ public static function publishRaw($projectName, $routeKey, $sendParams) { - $amqp = new AmqpHelper; + $amqp = new self(); $amqp->setProject($projectName); $queue = $amqp->getQueueConfig($routeKey); - // Получаем массив ключей маршрутизации из конфига. - // Если массив пустой или некорректный, откатываемся к дефолтному названию очереди. - $routingKeys = (!empty($queue['routing']) && is_array($queue['routing'])) - ? $queue['routing'] - : [$queue['name']]; + $routingKeys = (!empty($queue['routing']) && is_array($queue['routing'])) ? $queue['routing'] : [$queue['name']]; - $exchange = $amqp->getExchange($queue); $payload = json_encode($sendParams); - // Отправляем сообщение для каждого ключа маршрутизации - foreach ($routingKeys as $routingKey) { - $exchange->publish( - $payload, - $routingKey, - AMQP_NOPARAM, - ['delivery_mode' => 2, 'content_type' => 'application/json'] - ); + $send = function () use ($amqp, $queue, $routingKeys, $payload) + { + $exchange = $amqp->getExchange($queue); + foreach ($routingKeys as $routingKey) + { + $exchange->publish( + $payload, + $routingKey, + AMQP_NOPARAM, + ['delivery_mode' => 2, 'content_type' => 'application/json'] + ); + } + }; + + try + { + $send(); + } catch (\AMQPExchangeException | \AMQPChannelException | \AMQPConnectionException $e) + { + self::resetCache(); + $send(); } AmqpLoger::log('producer', $sendParams, $routeKey); @@ -248,15 +274,13 @@ class AmqpHelper */ public static function publish($projectName, $routeKey, $params, $object, $api = '1.0') { - $sendParams = [ - 'id' => uniqid() . '-' . uniqid(), - 'date' => date(\DateTime::ISO8601), - 'object' => $object, - 'api' => $api, - 'params' => $params - ]; - AmqpHelper::publishRaw($projectName, $routeKey, $sendParams); - return $sendParams; + return self::publishRaw($projectName, $routeKey, [ + 'id' => uniqid() . '-' . uniqid(), + 'date' => date(\DateTime::ISO8601), + 'object' => $object, + 'api' => $api, + 'params' => $params, + ]); } /** @@ -268,14 +292,12 @@ class AmqpHelper */ public static function sendMail($projectName, $routeKey, $params, $code) { - $sendParams = [ - 'id' => uniqid() . '-' . uniqid(), - 'date' => date(\DateTime::ISO8601), - 'code' => $code, - 'params' => $params - ]; - AmqpHelper::publishRaw($projectName, $routeKey, $sendParams); - return $sendParams; + return self::publishRaw($projectName, $routeKey, [ + 'id' => uniqid() . '-' . uniqid(), + 'date' => date(\DateTime::ISO8601), + 'code' => $code, + 'params' => $params, + ]); } /** @@ -287,15 +309,11 @@ class AmqpHelper */ public static function sendEvent($projectName, $routeKey, $params, $code) { - $sendParams = [ - 'id' => uniqid() . '-' . uniqid(), - 'date' => date(\DateTime::ISO8601), - 'code' => $code, - 'params' => $params - ]; - AmqpHelper::publishRaw($projectName, $routeKey, $sendParams); - return $sendParams; + return self::publishRaw($projectName, $routeKey, [ + 'id' => uniqid() . '-' . uniqid(), + 'date' => date(\DateTime::ISO8601), + 'code' => $code, + 'params' => $params, + ]); } - - }