Message.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  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. private $_corr_id;
  18. public function __construct($queueName)
  19. {
  20. $this->_connect = self::connect();
  21. $this->_channel = $this->_connect->channel();
  22. $this->_callback_queue = $queueName;
  23. }
  24. /**
  25. * [发送信息]
  26. * @author: libingke
  27. * @param string $body 消息主体
  28. * @param string $routing_key
  29. * @return bool
  30. */
  31. public function send($body, $routing_key)
  32. {
  33. $properties = [
  34. 'content_type' => 'text/plain',
  35. 'correlation_id' => uniqid(),
  36. 'reply_to' => $this->_callback_queue
  37. ];
  38. if (is_string($body)) {
  39. $msg = new AMQPMessage( (string) $body, $properties);
  40. $this->_channel->basic_publish($msg, '', $routing_key);
  41. }
  42. return true;
  43. }
  44. /**
  45. * [批量发送信息]
  46. * @author: libingke
  47. * @param string $body 消息主体
  48. * @param string $routing_key
  49. * @return array 返回数据
  50. */
  51. public function batchSend($body, $routing_key = '')
  52. {
  53. }
  54. /**
  55. * [消费信息]
  56. * @author: libingke
  57. * @param string $queue 队列名称
  58. * @param string $str
  59. * @return bool
  60. */
  61. public function receive($queue)
  62. {
  63. $callback = function($msg) {
  64. echo $msg->get('correlation_id');
  65. echo " [x] Received ", $msg->body, "\n";
  66. $msg->delivery_info['channel']->basic_ack($msg->delivery_info['delivery_tag']);
  67. };
  68. $this->_channel->basic_qos(null, 1, null);
  69. $this->_channel->basic_consume(
  70. $queue, '', false, false, false, false,
  71. $callback
  72. );
  73. /*while(count($this->_channel->callbacks)) {
  74. $this->_channel->wait();
  75. }*/
  76. return true;
  77. }
  78. /**
  79. * [批量消费信息]
  80. * @author: libingke
  81. * @param string $queue 队列名称
  82. * @param string $arr
  83. * @return array 返回数据
  84. */
  85. public function batchReceive($queue, $arr)
  86. {
  87. }
  88. /**
  89. * [删除信息]
  90. * @author: libingke
  91. */
  92. public function delete($message)
  93. {
  94. }
  95. }