rain
2024-06-14 8d9a2d656e4ae007590c622e5f7c228adacdca49
src/main/java/com/dji/sample/component/mqtt/service/impl/MessageSenderServiceImpl.java
@@ -1,14 +1,17 @@
package com.dji.sample.component.mqtt.service.impl;
import com.dji.sample.amap.model.ReceiverData;
import com.dji.sample.component.mqtt.model.*;
import com.dji.sample.component.mqtt.service.IMessageSenderService;
import com.dji.sample.component.mqtt.service.IMqttMessageGateway;
import com.dji.sample.component.rabbitmq.config.MqttMsgProxyProducer;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.TypeMismatchException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
@@ -31,14 +34,42 @@
    @Autowired
    private ObjectMapper mapper;
    @Value("${spring.rabbitmq.is-open}")
    private Boolean sendRabbitMQ;
    @Autowired
    private MqttMsgProxyProducer mqttMsgProxyProducer;
    public void publish(String topic, CommonTopicResponse response) {
        this.publish(topic, 1, response);
    }
    public void sendRabbitMQ(String topic, Object data) {
        try {
            if (sendRabbitMQ) {
                sendRabbitMQ(topic.replace("/", ".") + ".response", mapper.writeValueAsBytes(data));
            }
        } catch (Exception e) {
            log.error("消息发送失败2:", e);
        }
    }
    private void sendRabbitMQ(String topic, byte[] bytes) {
        //发送操作消息至mqtt同时发送到rabbitMQ
        try {
            if (sendRabbitMQ) {
                mqttMsgProxyProducer.publish(topic, bytes);
            }
        } catch (Exception e) {
            log.error("消息发送失败:", e);
        }
    }
    public void publish(String topic, int qos, CommonTopicResponse response) {
        try {
            log.info("send topic: {}, payload: {}", topic, response.toString());
            messageGateway.publish(topic, mapper.writeValueAsBytes(response), qos);
            byte[] bytes = mapper.writeValueAsBytes(response);
            sendRabbitMQ(topic, bytes);
            messageGateway.publish(topic, bytes, qos);
        } catch (JsonProcessingException e) {
            log.info("Failed to publish the message. {}", response.toString());
            e.printStackTrace();
@@ -51,6 +82,9 @@
    public <T> T publishWithReply(Class<T> clazz, String topic, CommonTopicResponse response, int retryTime) {
        AtomicInteger time = new AtomicInteger(0);
        ReceiverData receiverData = new ReceiverData();
        receiverData.setTid(response.getTid());
        receiverData.setBid(response.getBid());
        // Retry three times
        while (time.getAndIncrement() <= retryTime) {
            this.publish(topic, response);
@@ -62,15 +96,21 @@
            // Need to match tid and bid.
            if (Objects.nonNull(receiver) && receiver.getTid().equals(response.getTid()) &&
                    receiver.getBid().equals(response.getBid())) {
                receiverData.setReceiver(receiver.getData());
                if (clazz.isAssignableFrom(receiver.getData().getClass())) {
//                    sendRabbitMQ(topic, receiverData); 设备会单独发一条操作响应消息
                    return receiver.getData();
                }
                receiverData.setError("类型转换异常:" + clazz.getTypeName());
                sendRabbitMQ(topic, receiverData);
                throw new TypeMismatchException(receiver.getData(), clazz);
            }
            // It must be guaranteed that the tid and bid of each message are different.
            response.setBid(UUID.randomUUID().toString());
            response.setTid(UUID.randomUUID().toString());
        }
        receiverData.setError("没有收到消息回复");
        sendRabbitMQ(topic, receiverData);
        throw new RuntimeException("没有收到消息回复。");
    }