| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111 |
- <?php
- /**
- * 库存管理消费者
- * 处理花材库存补充、扣减等库存操作
- */
- namespace common\components\rabbitmq;
- use mikemadisonweb\rabbitmq\components\ConsumerInterface;
- use PhpAmqpLib\Message\AMQPMessage;
- use Yii;
- class stockConsumer implements ConsumerInterface
- {
- /**
- * 执行消费者逻辑
- *
- * @param AMQPMessage $msg 消息对象
- * @return string 消息处理结果
- *
- * ConsumerInterface::MSG_ACK - 确认消息(标记为已处理)并从队列中删除
- * ConsumerInterface::MSG_REJECT - 拒绝并从队列中删除消息
- * ConsumerInterface::MSG_REQUEUE - 拒绝并重新入队消息
- */
- public function execute(AMQPMessage $msg)
- {
- try {
- // 反序列化消息体
- $data = unserialize($msg->body);
-
- if (!is_array($data)) {
- Yii::error("Invalid stock message format: {$msg->body}", 'rabbitmq.stock');
- return ConsumerInterface::MSG_REJECT;
- }
-
- Yii::info("Processing stock message: " . json_encode($data), 'rabbitmq.stock');
-
- // 根据操作类型分发处理
- $action = $data['action'] ?? null;
- switch ($action) {
- case 'add':
- $result = $this->handleAddStock($data);
- break;
- case 'reduce':
- $result = $this->handleReduceStock($data);
- break;
- case 'adjust':
- $result = $this->handleAdjustStock($data);
- break;
- default:
- Yii::warning("Unknown stock action: {$action}", 'rabbitmq.stock');
- $result = false;
- }
-
- if ($result) {
- Yii::info("Stock message processed successfully", 'rabbitmq.stock');
- return ConsumerInterface::MSG_ACK;
- } else {
- Yii::error("Stock message processing failed", 'rabbitmq.stock');
- return ConsumerInterface::MSG_REQUEUE;
- }
-
- } catch (\Exception $e) {
- Yii::error("Stock consumer exception: " . $e->getMessage(), 'rabbitmq.stock');
- return ConsumerInterface::MSG_REQUEUE;
- }
- }
-
- /**
- * 处理库存补充(增加)
- *
- * @param array $data 消息数据,包含 material_id, quantity 等
- * @return bool 处理结果
- */
- private function handleAddStock($data)
- {
- // TODO: 实现库存增加业务逻辑
- // 调用对应的 Service 或 Class 层处理
- // 例如: StockClass::addStock($data);
- return true;
- }
-
- /**
- * 处理库存扣减
- *
- * @param array $data 消息数据,包含 material_id, quantity 等
- * @return bool 处理结果
- */
- private function handleReduceStock($data)
- {
- // TODO: 实现库存扣减业务逻辑
- // 调用对应的 Service 或 Class 层处理
- // 例如: StockClass::reduceStock($data);
- return true;
- }
-
- /**
- * 处理库存调整
- *
- * @param array $data 消息数据,包含 material_id, quantity, type 等
- * @return bool 处理结果
- */
- private function handleAdjustStock($data)
- {
- // TODO: 实现库存调整业务逻辑
- // 调用对应的 Service 或 Class 层处理
- // 例如: StockClass::adjustStock($data);
- return true;
- }
- }
|