package com.xcong.excoin.modules.station.producer; import com.alibaba.fastjson.JSON; import com.xcong.excoin.configurations.RabbitMqConfig; import com.xcong.excoin.modules.station.model.GateCommand; import lombok.extern.slf4j.Slf4j; import org.springframework.amqp.rabbit.connection.CorrelationData; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.UUID; /** * Station → JAR 指令发送器(精准路由到 QUEUE_GATE_CMD_{apiKeyMd5}) */ @Slf4j @Component public class CmdProducer { private final RabbitTemplate rabbitTemplate; /** RabbitTemplate 是 prototype,必须用构造器注入 */ @Autowired public CmdProducer(RabbitTemplate rabbitTemplate) { this.rabbitTemplate = rabbitTemplate; } /** * 发送指令到目标 JAR * * @param apiKeyMd5 目标 apiKey MD5 * @param type START / STOP */ public void sendCommand(String apiKeyMd5, String type) { sendCommand(apiKeyMd5, type, null); } /** * 发送带 payload 的指令到目标 JAR * * @param apiKeyMd5 目标 apiKey MD5 * @param type START / STOP / UPDATE_CONFIG * @param payload 指令附加数据(JSON),可为 null */ public void sendCommand(String apiKeyMd5, String type, String payload) { GateCommand cmd = GateCommand.builder() .commandId(UUID.randomUUID().toString()) .commandType(type) .apiKeyMd5(apiKeyMd5) .timestamp(System.currentTimeMillis()) .payload(payload) .build(); String routingKey = "cmd." + apiKeyMd5; CorrelationData cd = new CorrelationData(cmd.getCommandId()); rabbitTemplate.convertAndSend(RabbitMqConfig.EXCHANGE_GATE, routingKey, JSON.toJSONString(cmd), cd); log.info("[Station] 发送指令: type={}, apiKeyMd5={}, cmdId={}, routingKey={}", type, apiKeyMd5, cmd.getCommandId(), routingKey); } }