disconnect() public method

This method will close an open connection with the AMQP broker.
public disconnect ( ) : boolean
return boolean true if connection was successfully closed, false otherwise.
 /**
  * @param array $event
  * @return bool
  */
 public function publish($event = [])
 {
     try {
         if (!$this->connection->isConnected()) {
             $this->connection->connect();
         }
         list($message, $attributes) = $this->prepareMessage($event);
         $result = $this->getExchange()->publish($message, null, AMQP_NOPARAM, $attributes);
         $this->connection->disconnect();
         return $result;
     } catch (\Exception $e) {
         return false;
     }
 }
Ejemplo n.º 2
0
 /**
  * Send an activity notice using AMQP
  * @param ActivityNotice $notice
  * @return bool
  */
 public function sendActivityNotice($notice)
 {
     if (!isset($notice)) {
         return false;
     }
     /** @var array $setting */
     $setting = $this->params['amqpSetting'];
     try {
         if ($this->amqpClientLibrary == "PhpAmqpLib") {
             $connection = new AMQPStreamConnection($setting['host'], $setting['port'], $setting['user'], $setting['password']);
             $channel = $connection->channel();
             $msg = new AMQPMessage(JsonHelper::encode($notice));
             $channel->basic_publish($msg, $setting['exchangeName'], $setting['routingKey']);
             $channel->close();
             $connection->close();
         } elseif ($this->amqpClientLibrary == "PECL") {
             $connection = new \AMQPConnection(['host' => $setting['host'], 'port' => $setting['port'], 'login' => $setting['user'], 'password' => $setting['password']]);
             $connection->connect();
             if ($connection->isConnected()) {
                 $channel = new \AMQPChannel($connection);
                 $exchange = new \AMQPExchange($channel);
                 $exchange->setName($setting['exchangeName']);
                 $exchange->publish(JsonHelper::encode($notice), $setting['routingKey']);
                 $connection->disconnect();
             }
         } else {
             return false;
         }
     } catch (\Exception $e) {
         return false;
     }
     return true;
 }
Ejemplo n.º 3
0
 /**
  * @inheritdoc
  */
 public function disconnect()
 {
     if ($this->options->getPersistent()) {
         $this->connection->pdisconnect();
     } else {
         $this->connection->disconnect();
     }
 }
Ejemplo n.º 4
0
 /**
  * Post a task to exchange specified in $details
  * @param AMQPConnection $connection Connection object
  * @param array $details Array of connection details
  * @param string $task JSON-encoded task
  * @param array $params AMQP message parameters
  */
 function PostToExchange($connection, $details, $task, $params)
 {
     $ch = new AMQPChannel($connection);
     $xchg = new AMQPExchange($ch);
     $xchg->setName($details['exchange']);
     $success = $xchg->publish($task, $details['binding'], 0, $params);
     $connection->disconnect();
     return $success;
 }
Ejemplo n.º 5
0
 public function main()
 {
     $connection = new \AMQPConnection($this->config->get('mq'));
     try {
         $connection->connect();
         if (!$connection->isConnected()) {
             $this->logging->exception("Cannot connect to the broker!" . PHP_EOL);
         }
         $this->channel = new \AMQPChannel($connection);
         $this->exchange = new \AMQPExchange($this->channel);
         $this->exchange->setName($this->exchangeName);
         $this->exchange->setType(AMQP_EX_TYPE_DIRECT);
         //direct类型
         $this->exchange->setFlags(AMQP_DURABLE);
         //持久化
         $this->exchange->declareExchange();
         //echo "Exchange Status:".$this->exchange->declare()."\n";
         //创建队列
         $this->queue = new \AMQPQueue($this->channel);
         $this->queue->setName($this->queueName);
         $this->queue->setFlags(AMQP_DURABLE);
         //持久化
         $this->queue->declareQueue();
         $bind = $this->queue->bind($this->exchangeName, $this->routeKey);
         //echo "Message Total:".$this->queue->declare()."\n";
         //绑定交换机与队列,并指定路由键
         //echo 'Queue Bind: '.$bind."\n";
         //阻塞模式接收消息
         //while(true){
         //for($i=0; $i< self::loop ;$i++){
         //$this->queue->consume('processMessage', AMQP_AUTOACK); //自动ACK应答
         $this->queue->consume(function ($envelope, $queue) {
             //print_r($envelope);
             //print_r($queue);
             $speed = microtime(true);
             $msg = $envelope->getBody();
             $result = $this->loader($msg);
             $queue->ack($envelope->getDeliveryTag());
             //手动发送ACK应答
             //$this->logging->info(''.$msg.' '.$result)
             $this->logging->debug('Protocol: ' . $msg . ' ');
             $this->logging->debug('Result: ' . $result . ' ');
             $this->logging->debug('Time: ' . (microtime(true) - $speed) . '');
         });
         $this->channel->qos(0, 1);
         //echo "Message Total:".$this->queue->declare()."\n";
         //}
     } catch (\AMQPConnectionException $e) {
         $this->logging->exception($e->__toString());
     } catch (\Exception $e) {
         $this->logging->exception($e->__toString());
         $connection->disconnect();
     }
 }
Ejemplo n.º 6
0
 function getBrokerStatus()
 {
     $amqpConnection = new AMQPConnection();
     $amqpConnection->setLogin("guest");
     $amqpConnection->setPassword("guest");
     $amqpConnection->setVhost("/");
     $amqpConnection->connect();
     if (!$amqpConnection->isConnected()) {
         log("info", "Cannot connect to the broker!");
         return false;
     }
     $amqpConnection->disconnect();
     return true;
 }
Ejemplo n.º 7
0
/**
 * 批量打入v3work_seo_pdrec数据,用于预热本企业推荐产品
 */
function writeRMQ($exchangeName = 'v3www', $router, $data = '')
{
    $cfg = array('host' => '192.168.8.18', 'port' => '5672', 'login' => 'v3work', 'password' => 'gc7232275', 'vhost' => '/');
    if (empty($exchangeName) || empty($data) || empty($cfg)) {
        return false;
    }
    $reTryNum = 3;
    $errMsg = array();
    do {
        try {
            //建立到rmq服务器链接
            $connection = new AMQPConnection($cfg);
            $connection->connect();
            //建立channel对象
            $channel = new AMQPChannel($connection);
            //建立交换机
            $exchange = new AMQPExchange($channel);
            $exchange->setName($exchangeName);
            $exchange->setType(AMQP_EX_TYPE_DIRECT);
            $exchange->setFlags(AMQP_DURABLE);
            $exchange->declare();
            $routingKey = $router;
            //发消息
            $ret = $exchange->publish($data, $routingKey, AMQP_NOPARAM, array('delivery_mode' => '2'));
            //关闭链接
            $connection->disconnect();
            return $ret;
        } catch (Exception $e) {
            $connection->disconnect();
            $errMsg[] = $e->getMessage();
            usleep(5000);
            $reTryNum -= 1;
        }
    } while ($reTryNum);
    return false;
}
Ejemplo n.º 8
0
 public static function main()
 {
     self::$pool = new Pool(MAX_CONCURRENCY_JOB, \CALLWorker::class, []);
     $conn_args = (require 'mq.config.php');
     $e_name = 'e_linvo';
     //交换机名
     $q_name = 'q_linvo';
     //队列名
     $k_route = 'key_1';
     //路由key
     //创建连接和channel
     $conn = new AMQPConnection($conn_args);
     if (!$conn->connect()) {
         write_log('mq.hx9999.com 无法连接上');
         return;
     }
     $channel = new AMQPChannel($conn);
     //创建交换机
     $ex = new AMQPExchange($channel);
     $ex->setName($e_name);
     $ex->setType(AMQP_EX_TYPE_DIRECT);
     //direct类型
     $ex->setFlags(AMQP_DURABLE);
     //持久化
     //创建队列
     $q = new AMQPQueue($channel);
     $q->setName($q_name);
     $q->setFlags(AMQP_DURABLE);
     //持久化
     while (True) {
         $q->consume(function ($envelope, $queue) {
             $msg = $envelope->getBody();
             $queue->ack($envelope->getDeliveryTag());
             //手动发送ACK应答
             self::$pool->submit(new Sendsms($msg));
         });
     }
     self::$pool->shutdown();
     $conn->disconnect();
     //睡眠
     sleep(5);
 }
Ejemplo n.º 9
0
 public function getProxy($https = false)
 {
     if ($https) {
         $queueName = 'q_proxy_https';
     } else {
         $queueName = 'q_proxy';
     }
     $params = array('host' => '10.168.45.191', 'port' => 5672, 'login' => 'guest', 'password' => 'guest', 'vhost' => '/kwd');
     $conn = new AMQPConnection($params);
     $conn->connect();
     $channel = new AMQPChannel($conn);
     $queue = new AMQPQueue($channel);
     $queue->setName($queueName);
     $message = $queue->get(AMQP_AUTOACK);
     $proxy = $message->getBody();
     while (!$this->_testProxy($proxy, $https)) {
         $message = $queue->get(AMQP_AUTOACK);
         $proxy = $message->getBody();
     }
     $conn->disconnect();
     return $proxy;
 }
Ejemplo n.º 10
0
/**
 * 批量打入v3work_seo_pdrec数据,用于预热本企业推荐产品
 */
function writeRMQ($exchangeName = 'v3cb', $routingKey, $data = '')
{
    global $cfg;
    if (empty($exchangeName) || empty($data) || empty($cfg)) {
        return false;
    }
    $reTryNum = 3;
    $errMsg = array();
    do {
        try {
            //建立到rmq服务器链接
            $connection = new AMQPConnection($cfg);
            $connection->connect();
            //建立channel对象
            $channel = new AMQPChannel($connection);
            //建立交换机
            $exchange = new AMQPExchange($channel);
            $exchange->setName($exchangeName);
            $exchange->setType(AMQP_EX_TYPE_DIRECT);
            $exchange->setFlags(AMQP_DURABLE);
            $exchange->declare();
            //发消息
            $ret = $exchange->publish($data, $routingKey, AMQP_NOPARAM, array('delivery_mode' => '2'));
            //关闭链接
            $connection->disconnect();
            return $ret;
        } catch (Exception $e) {
            $connection->disconnect();
            $errMsg[] = $e->getMessage();
            usleep(5000);
            $reTryNum -= 1;
        }
    } while ($reTryNum);
    return false;
}
Ejemplo n.º 11
0
 /**
  * @return bool
  */
 public function disconnect()
 {
     if (true === $this->connection->isConnected()) {
         return $this->connection->disconnect();
     }
 }
 /**
  * Establishes disconnection to MQ
  * @param AMQPConnection $amqpConnection
  * @return boolean
  */
 public function amqpDisconnect(\AMQPConnection $amqpConnection)
 {
     if (!$amqpConnection->disconnect()) {
         throw new \Exception("Failed to disconnect from rabbitmq server");
     }
     return true;
 }
Ejemplo n.º 13
0
 public function it_should_ensure_disconnection_on_same_endpoint(\AMQPConnection $connection)
 {
     $connection->isConnected()->willReturn(false);
     $connection->disconnect()->shouldNotBeCalled();
     $this->disconnect();
 }
 private function stopConsumer()
 {
     $this->connection->disconnect();
     exit("\nconsumer-stop signal received\n");
 }
Ejemplo n.º 15
0
 /**
  * @inheritdoc
  */
 public function close()
 {
     return $this->delegate->disconnect();
 }
Ejemplo n.º 16
0
 /**
  * Close connection and channel
  *
  * @return $this
  */
 public function __destruct()
 {
     if ($this->connection) {
         $this->connection->disconnect();
     }
 }
Ejemplo n.º 17
0
 /**
  * Cleanly close the connection
  * 
  */
 function __destruct()
 {
     if ($this->connected()) {
         $this->_connection->disconnect();
     }
 }
Ejemplo n.º 18
0
$rabbit->connect();
$channel = new AMQPChannel($rabbit);
$queue = new AMQPExchange($channel);
$queue->setName('amq.direct');
/**
 * Добавляем очередь откуда будем брать страницы
 */
$q = new AMQPQueue($channel);
$q->setName('images_to_scan');
$q->declare();
$q->bind('amq.direct', 'analyze_image');
/**
 * Обрабатываем пока в очереди не закончатся сообщения
 */
while (true) {
    $image = $q->get();
    if ($image) {
        $url = $image->getBody();
        echo "Checking: {$url}\n";
        $analyzer = new ImageAnalyzer($url);
        /**
         * Если картинка еще не была проанализирована, обрабатываем и добавляем в индекс
         */
        $analyzer->analyze();
        $q->ack($image->getDeliveryTag());
    } else {
        sleep(1);
    }
}
$rabbit->disconnect();
Ejemplo n.º 19
0
 /**
  * Close RabbitMQ
  *
  * @access public
  * @return void
  */
 public function __destruct()
 {
     $this->connect->disconnect();
 }
 /**
  * @return mixed
  */
 public function close()
 {
     $this->connection->disconnect();
 }
$connection = new AMQPConnection();
$connection->setHost('127.0.0.1');
$connection->setLogin('guest');
$connection->setPassword('guest');
$connection->connect();
//Declare Channel
$channel = new AMQPChannel($connection);
$routing_key = $severity = isset($argv[1]) && !empty($argv[1]) ? $argv[1] : 'info';
$message = implode(' ', array_slice($argv, 2));
if (empty($message)) {
    $message = 'Hello World!';
}
try {
    //Declare Exchange
    $exchange_name = 'direct_logs';
    $exchange = new AMQPExchange($channel);
    $exchange->setType(AMQP_EX_TYPE_DIRECT);
    $exchange->setName($exchange_name);
    $exchange->declareExchange();
    $queue = new AMQPQueue($channel);
    $queue->setFlags(AMQP_EXCLUSIVE);
    $queue->setName('monitor.1');
    $queue->declareQueue();
    $queue->bind($exchange_name, $routing_key);
    $exchange->publish($message, $routing_key);
    echo " [x] Sent {$severity}:{$message}", PHP_EOL;
} catch (Exception $ex) {
    print_r($ex);
}
$connection->disconnect();
Ejemplo n.º 22
0
 public function disconnect()
 {
     try {
         $this->rawConnection->disconnect();
     } catch (\AMQPConnectionException $e) {
         ClientHelper::throwRightException($e);
     }
 }
<?php

$cnn = new AMQPConnection();
$ret = $cnn->connect();
$ch = new AMQPChannel($cnn);
$ex = new AMQPExchange($ch);
$ex->setName('exchange-' . microtime(true));
$ex->setType(AMQP::TYPE_FANOUT);
$ex->setArguments(array("x-ha-policy" => "all"));
$ex->setFlags(AMQP::PASSIVE | AMQP::DURABLE | AMQP::AUTODELETE | AMQP::INTERNAL);
var_dump($ex);
$ex->setFlags(AMQP::NOPARAM);
echo $ex->getFlags();
$ex->setFlags(2);
echo $ex->getFlags();
$ex->setFlags(0);
echo $ex->getFlags();
$ex->setFlags(2);
echo $ex->getFlags();
// --EXPECT-- 0202
$cnn->disconnect();
 /**
  * {@inheritDoc}
  */
 protected function tearDownAmqp()
 {
     $this->conn->disconnect();
 }