1
0

RabbitMqServer.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. <?php
  2. namespace components;
  3. use PhpAmqpLib\Channel\AMQPChannel;
  4. use PhpAmqpLib\Connection\AMQPConnection;
  5. use PhpAmqpLib\Message\AMQPMessage;
  6. use PhpAmqpLib\Connection\AMQPStreamConnection;
  7. use PhpAmqpLib\Exception\AMQPConnectionException;
  8. use yii\base\Component;
  9. use yii\base\ErrorException;
  10. use yii\base\Event;
  11. use yii\base\Exception;
  12. class RabbitMqServer{
  13. CONST HOST = "172.30.118.225";
  14. // CONST HOST = "localhost";
  15. CONST PORT = 5673; //默认5672
  16. CONST USER = "guest"; //用户名
  17. CONST PASS = "guest";//密码
  18. private $conn_args = array('host'=>'127.0.0.1','port'=>'5672','login'=>'guest','password'=>'guest','vhost'=>'/') ;
  19. private $channel;
  20. private $e_name = 'glitzcloud';
  21. public function __construct(){
  22. //创建Exchannel
  23. $this->channel = $this->connrabbit($this->conn_args);
  24. if(!$this->channel){
  25. echo 'Cannot Connect to the broker';
  26. exit();
  27. }
  28. }
  29. /*
  30. *创建RabbitMq Message
  31. */
  32. public function setRabbit($message,$k_route,$e_name=''){
  33. if(empty($e_name)){
  34. $e_name = $this->e_name;
  35. }
  36. $channel = $this->channel;
  37. $res1=$channel->queue_declare($e_name, false, true, false, false);//声明
  38. $msg = new AMQPMessage($message,
  39. array(
  40. 'delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT,
  41. // 'correlation_id' => 1111111111,
  42. // 'reply_to' => 'show'
  43. )
  44. );
  45. $res= $channel->basic_publish($msg,'yang',$e_name);
  46. $channel->close();
  47. return true;
  48. }
  49. /*
  50. *获取RabbitMq Message
  51. */
  52. public function getRabbit($k_route,$q_name){
  53. //1.权限问题
  54. //2.获取方法没有
  55. if(empty($e_name)){
  56. $e_name = $this->e_name;
  57. }
  58. $channel = $this->channel;
  59. // $channel->queue_declare($e_name, false, true, false, false);//声明
  60. // $this->channel->queue_declare($e_name,true, true);
  61. // $channel->exchange_declare('yang', '', false, true, false);
  62. // $channel->queue_bind('', '','');
  63. // $channel->basic_get();
  64. // $messages = $channel->get(AMQP_AUTOACK);
  65. // if(is_object( $messages))
  66. // return $messages->getBody();
  67. // return $messages;
  68. }
  69. /**
  70. *链接RabbitMQ
  71. */
  72. protected function connrabbit($conn_args){
  73. $conn = new AMQPStreamConnection(
  74. \Yii::$app->params['rabbithost'], self::PORT, self::USER, self::PASS); //建立连接
  75. if(!$conn->connectOnConstruct()){
  76. return false;
  77. }
  78. $channel = new AMQPChannel($conn);
  79. return $channel;
  80. }
  81. }