customConsumer.php 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. <?php
  2. /**
  3. * 客户操作消费者
  4. * 处理客户创建、修改等业务操作
  5. */
  6. namespace common\components\rabbitmq;
  7. use mikemadisonweb\rabbitmq\components\ConsumerInterface;
  8. use PhpAmqpLib\Message\AMQPMessage;
  9. use Yii;
  10. class customConsumer implements ConsumerInterface
  11. {
  12. /**
  13. * 执行消费者逻辑
  14. *
  15. * @param AMQPMessage $msg 消息对象
  16. * @return string 消息处理结果
  17. *
  18. * ConsumerInterface::MSG_ACK - 确认消息(标记为已处理)并从队列中删除
  19. * ConsumerInterface::MSG_REJECT - 拒绝并从队列中删除消息
  20. * ConsumerInterface::MSG_REQUEUE - 拒绝并重新入队消息
  21. */
  22. public function execute(AMQPMessage $msg)
  23. {
  24. try {
  25. // 反序列化消息体
  26. $data = unserialize($msg->body);
  27. if (!is_array($data)) {
  28. Yii::error("Invalid custom message format: {$msg->body}", 'rabbitmq.custom');
  29. return ConsumerInterface::MSG_REJECT;
  30. }
  31. Yii::info("Processing custom message: " . json_encode($data), 'rabbitmq.custom');
  32. // 根据操作类型分发处理
  33. $action = $data['action'] ?? null;
  34. switch ($action) {
  35. case 'create':
  36. $result = $this->handleCreateCustom($data);
  37. break;
  38. case 'update':
  39. $result = $this->handleUpdateCustom($data);
  40. break;
  41. case 'delete':
  42. $result = $this->handleDeleteCustom($data);
  43. break;
  44. default:
  45. Yii::warning("Unknown custom action: {$action}", 'rabbitmq.custom');
  46. $result = false;
  47. }
  48. if ($result) {
  49. Yii::info("Custom message processed successfully", 'rabbitmq.custom');
  50. return ConsumerInterface::MSG_ACK;
  51. } else {
  52. Yii::error("Custom message processing failed", 'rabbitmq.custom');
  53. return ConsumerInterface::MSG_REQUEUE;
  54. }
  55. } catch (\Exception $e) {
  56. Yii::error("Custom consumer exception: " . $e->getMessage(), 'rabbitmq.custom');
  57. return ConsumerInterface::MSG_REQUEUE;
  58. }
  59. }
  60. /**
  61. * 处理客户创建
  62. *
  63. * @param array $data 消息数据
  64. * @return bool 处理结果
  65. */
  66. private function handleCreateCustom($data)
  67. {
  68. // TODO: 实现客户创建业务逻辑
  69. // 调用对应的 Service 或 Class 层处理
  70. return true;
  71. }
  72. /**
  73. * 处理客户更新
  74. *
  75. * @param array $data 消息数据
  76. * @return bool 处理结果
  77. */
  78. private function handleUpdateCustom($data)
  79. {
  80. // TODO: 实现客户更新业务逻辑
  81. // 调用对应的 Service 或 Class 层处理
  82. return true;
  83. }
  84. /**
  85. * 处理客户删除
  86. *
  87. * @param array $data 消息数据
  88. * @return bool 处理结果
  89. */
  90. private function handleDeleteCustom($data)
  91. {
  92. // TODO: 实现客户删除业务逻辑
  93. // 调用对应的 Service 或 Class 层处理
  94. return true;
  95. }
  96. }