67 lines
2.3 KiB
Java
67 lines
2.3 KiB
Java
package com.muyu.mqtt;
|
||
|
||
|
||
|
||
import com.alibaba.fastjson.JSON;
|
||
import com.muyu.mqtt.dao.MessageData;
|
||
import com.muyu.utils.ConversionUtil;
|
||
import lombok.extern.log4j.Log4j2;
|
||
import org.apache.kafka.clients.producer.ProducerRecord;
|
||
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
|
||
import org.eclipse.paho.client.mqttv3.MqttCallback;
|
||
import org.eclipse.paho.client.mqttv3.MqttMessage;
|
||
import org.springframework.beans.factory.annotation.Autowired;
|
||
import org.springframework.kafka.core.KafkaAdmin;
|
||
import org.springframework.kafka.core.KafkaTemplate;
|
||
import org.springframework.stereotype.Service;
|
||
import java.util.concurrent.ExecutionException;
|
||
import java.util.concurrent.atomic.AtomicInteger;
|
||
|
||
/**
|
||
* 回执消息类 MessageCallbackService
|
||
*
|
||
* @author Yangle
|
||
* Date 2024/6/6 15:08
|
||
*/
|
||
@Service
|
||
@Log4j2
|
||
public class MessageCallbackService implements MqttCallback {
|
||
|
||
@Autowired
|
||
private KafkaTemplate kafkaTemplate;
|
||
@Autowired
|
||
private KafkaAdmin kafkaAdmin;
|
||
|
||
@Override
|
||
public void connectionLost(Throwable cause) {
|
||
System.out.println("connectionLost:"+cause.getMessage());
|
||
}
|
||
|
||
|
||
private static final AtomicInteger PARTITION_COUNTER = new AtomicInteger(0); // 假设NUM_PARTITIONS是已知的分区数量
|
||
private static final int NUM_PARTITIONS = 8; // 请根据实际情况设置分区数量
|
||
|
||
@Override
|
||
public void messageArrived(String topic, MqttMessage mqttMessage) {
|
||
log.info("topic:{}", topic);
|
||
log.info("Qos:{}", mqttMessage.getQos());
|
||
log.info("message content:{}", new String(mqttMessage.getPayload()));
|
||
|
||
String s = new String(mqttMessage.getPayload());
|
||
MessageData main = ConversionUtil.main(s);
|
||
|
||
// 准备ProducerRecord并发送到Kafka
|
||
String kafkaTopic = topic; // 假设MQTT主题与Kafka主题相同
|
||
String key = main.getVin(); // 使用vin作为key,如果适用
|
||
String value = JSON.toJSONString(main);
|
||
ProducerRecord<String, String> producerRecord = new ProducerRecord<>(kafkaTopic, key, value);
|
||
kafkaTemplate.send(producerRecord);// 注意:这里使用get()会阻塞直到发送完成,实际应用中可能需要异步处理
|
||
|
||
}
|
||
|
||
@Override
|
||
public void deliveryComplete(IMqttDeliveryToken token) {
|
||
System.out.println("deliveryComplete---------" + token.isComplete());
|
||
}
|
||
}
|