123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107 |
- <?php
- namespace components;
- use PhpAmqpLib\Channel\AMQPChannel;
- use PhpAmqpLib\Connection\AMQPConnection;
- use PhpAmqpLib\Message\AMQPMessage;
- use PhpAmqpLib\Connection\AMQPStreamConnection;
- use PhpAmqpLib\Exception\AMQPConnectionException;
- use yii\base\Component;
- use yii\base\ErrorException;
- use yii\base\Event;
- use yii\base\Exception;
- class RabbitMqServer{
- CONST HOST = "172.30.118.225";
- // CONST HOST = "localhost";
- CONST PORT = 5673; //默认5672
- CONST USER = "guest"; //用户名
- CONST PASS = "guest";//密码
- private $conn_args = array('host'=>'127.0.0.1','port'=>'5672','login'=>'guest','password'=>'guest','vhost'=>'/') ;
- private $channel;
- private $e_name = 'glitzcloud';
- public function __construct(){
- //创建Exchannel
- $this->channel = $this->connrabbit($this->conn_args);
- if(!$this->channel){
- echo 'Cannot Connect to the broker';
- exit();
- }
- }
- /*
- *创建RabbitMq Message
- */
- public function setRabbit($message,$k_route,$e_name=''){
- if(empty($e_name)){
- $e_name = $this->e_name;
- }
- $channel = $this->channel;
- $res1=$channel->queue_declare($e_name, false, true, false, false);//声明
- $msg = new AMQPMessage($message,
- array(
- 'delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT,
- // 'correlation_id' => 1111111111,
- // 'reply_to' => 'show'
- )
- );
- $res= $channel->basic_publish($msg,'yang',$e_name);
- $channel->close();
- return true;
- }
- /*
- *获取RabbitMq Message
- */
- public function getRabbit($k_route,$q_name){
- //1.权限问题
- //2.获取方法没有
- if(empty($e_name)){
- $e_name = $this->e_name;
- }
- $channel = $this->channel;
- // $channel->queue_declare($e_name, false, true, false, false);//声明
- // $this->channel->queue_declare($e_name,true, true);
- // $channel->exchange_declare('yang', '', false, true, false);
- // $channel->queue_bind('', '','');
- // $channel->basic_get();
- // $messages = $channel->get(AMQP_AUTOACK);
- // if(is_object( $messages))
- // return $messages->getBody();
- // return $messages;
- }
- /**
- *链接RabbitMQ
- */
- protected function connrabbit($conn_args){
- $conn = new AMQPStreamConnection(
- self::HOST, self::PORT, self::USER, self::PASS); //建立连接
- if(!$conn->connectOnConstruct()){
- return false;
- }
- $channel = new AMQPChannel($conn);
- return $channel;
- }
- }
|