Message.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. <?php
  2. namespace common\logic\Amqp;
  3. use PhpAmqpLib\Message\AMQPMessage;
  4. /**
  5. * 处理消息体逻辑
  6. * Class Message
  7. * @package common\logic\MQMessage
  8. * @author libingke
  9. */
  10. class Message extends Connect
  11. {
  12. private $_connect;
  13. private $_channel;
  14. private $_callback_queue;
  15. private $_result;
  16. private $_response;
  17. public function __construct($queueName)
  18. {
  19. $this->_connect = self::connect();
  20. $this->_channel = $this->_connect->channel();
  21. $this->_callback_queue = $queueName;
  22. }
  23. /**
  24. * [发送信息]
  25. * @author: libingke
  26. * @param string $body 消息主体
  27. * @param string $routing_key
  28. * @return bool
  29. */
  30. public function send($body, $routing_key)
  31. {
  32. $properties = [
  33. 'content_type' => 'text/plain',
  34. 'correlation_id' => uniqid(),
  35. 'reply_to' => $this->_callback_queue
  36. ];
  37. if (is_string($body)) {
  38. $msg = new AMQPMessage( (string) $body, $properties);
  39. $this->_channel->basic_publish($msg, '', $routing_key);
  40. }
  41. return true;
  42. }
  43. /**
  44. * [批量发送信息]
  45. * @author: libingke
  46. * @param $info
  47. * @param $queue
  48. */
  49. public function batchSend($info, $queue)
  50. {
  51. foreach ($info as $str) {
  52. $this->_channel->batch_basic_publish($str, '', $queue);
  53. }
  54. $this->_channel->publish_batch();
  55. }
  56. /**
  57. * [消费信息]
  58. * @author: libingke
  59. * @param string $queue 队列名称
  60. * @param string $str
  61. * @return bool
  62. */
  63. public function receive($queue)
  64. {
  65. $callback = function($msg) {
  66. echo $msg->get('correlation_id');
  67. echo " [x] Received ", $msg->body, "\n";
  68. $msg->delivery_info['channel']->basic_ack($msg->delivery_info['delivery_tag']);
  69. };
  70. $this->_channel->basic_qos(null, 1, null);
  71. $this->_channel->basic_consume(
  72. $queue, '', false, false, false, false,
  73. $callback
  74. );
  75. /*while(count($this->_channel->callbacks)) {
  76. $this->_channel->wait();
  77. }*/
  78. return true;
  79. }
  80. /**
  81. * [批量消费信息]
  82. * @author: libingke
  83. * @param string $queue 队列名称
  84. * @param string $arr
  85. * @return array 返回数据
  86. */
  87. public function batchReceive($queue, $arr)
  88. {
  89. }
  90. /**
  91. * [删除信息]
  92. * @author: libingke
  93. */
  94. public function delete($message)
  95. {
  96. }
  97. }