maven的pom.xml引入包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-integration</artifactId>
<version>2.3.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-stream</artifactId>
<version>5.3.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-mqtt</artifactId>
<version>5.3.4.RELEASE</version>
</dependency>
mqtt.yml配置文件
spring:
mqtt:
username: admin
password: beyond_2021
url: tcp://192.168.3.100:1883
client-id: data-clientId
server-id: data-serverId
data-topic: data/
will-topic: data-will
will-content: data server offline
completion-timeout: 10000
初始化MQTT配置bean
package com.beyond.config;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
import org.springframework.integration.annotation.IntegrationComponentScan;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.core.MessageProducer;
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.event.MqttConnectionFailedEvent;
import org.springframework.integration.mqtt.event.MqttMessageDeliveredEvent;
import org.springframework.integration.mqtt.event.MqttMessageSentEvent;
import org.springframework.integration.mqtt.event.MqttSubscribedEvent;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
import org.springframework.integration.mqtt.support.DefaultPahoMessageConverter;
import org.springframework.integration.mqtt.support.MqttHeaders;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessagingException;
import java.security.SecureRandom;
import java.util.Date;
@Configuration
@IntegrationComponentScan
public class MqttConfig {
private static final Logger log = LoggerFactory.getLogger(MqttConfig.class);
@Value("${spring.mqtt.username}")
private String username;
@Value("${spring.mqtt.password}")
private String password;
@Value("${spring.mqtt.url}")
private String hostUrl;
@Value("${spring.mqtt.client-id}")
private String clientId;
@Value("${spring.mqtt.server-id}")
private String serverId;
@Value("${spring.mqtt.data-topic:data/#}")
private String dataTopic;
@Value("${spring.mqtt.will-topic}")
private String willTopic;
@Value("${spring.mqtt.will-content}")
private String willContent;
@Value("${spring.mqtt.completion-timeout}")
private int completionTimeout ;
@Bean
public MqttConnectOptions getMqttConnectOptions(){
MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
mqttConnectOptions.setUserName(username);
mqttConnectOptions.setPassword(password.toCharArray());
mqttConnectOptions.setCleanSession(true);
mqttConnectOptions.setServerURIs(hostUrl.split(","));
mqttConnectOptions.setKeepAliveInterval(20);
mqttConnectOptions.setAutomaticReconnect(true);
mqttConnectOptions.setWill(willTopic, willContent.getBytes(), 2, false);
mqttConnectOptions.setMaxInflight(1000000);
return mqttConnectOptions;
}
@Bean
public MqttPahoClientFactory mqttClientFactory() {
DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
factory.setConnectionOptions(getMqttConnectOptions());
return factory;
}
@Bean
@ServiceActivator(inputChannel = "mqttOutboundChannel")
public MessageHandler mqttOutbound() {
String clientIdStr = clientId + new SecureRandom().nextInt(10);
MqttPahoMessageHandler messageHandler = new MqttPahoMessageHandler(clientIdStr, mqttClientFactory());
messageHandler.setAsync(true);
messageHandler.setAsyncEvents(true);
messageHandler.setDefaultTopic(dataTopic);
messageHandler.setDefaultQos(1);
return messageHandler;
}
@Bean
public MessageChannel mqttOutboundChannel() {
return new DirectChannel();
}
@Bean
public MessageChannel mqttInputChannel() {
return new DirectChannel();
}
@Bean
public MessageProducer inbound() {
String serverIdStr = serverId + new SecureRandom().nextInt(10);
MqttPahoMessageDrivenChannelAdapter adapter =
new MqttPahoMessageDrivenChannelAdapter(serverIdStr, mqttClientFactory(), dataTopic);
adapter.setCompletionTimeout(completionTimeout);
adapter.setConverter(new DefaultPahoMessageConverter());
adapter.setQos(1);
adapter.setOutputChannel(mqttInputChannel());
return adapter;
}
@Bean
@ServiceActivator(inputChannel = "mqttInputChannel")
public MessageHandler handler() {
return new MessageHandler() {
@Override
public void handleMessage(Message<?> message) throws MessagingException {
String payload = message.getPayload().toString();
String topic = message.getHeaders().get(MqttHeaders.RECEIVED_TOPIC).toString();
}
};
}
@EventListener(MqttConnectionFailedEvent.class)
public void mqttConnectionFailedEvent(MqttConnectionFailedEvent event) {
log.error("mqttConnectionFailedEvent连接mqtt失败: " +
"date={}, hostUrl={}, username={}, error={}",
new Date(), hostUrl, username, event.getCause().getMessage());
}
@EventListener(MqttMessageSentEvent.class)
public void mqttMessageSentEvent(MqttMessageSentEvent event) {
log.info("mqttMessageSentEvent发送信息: date={}, info={}", new Date(), event.toString());
}
@EventListener(MqttMessageDeliveredEvent.class)
public void mqttMessageDeliveredEvent(MqttMessageDeliveredEvent event) {
log.info("mqttMessageDeliveredEvent发送成功信息: date={}, info={}", new Date(), event.toString());
}
@EventListener(MqttSubscribedEvent.class)
public void mqttSubscribedEvent(MqttSubscribedEvent event) {
log.info("mqttSubscribedEvent订阅成功信息: date={}, info={}", new Date(), event.toString());
}
}
mqtt发送数据网关配置
package com.beyond.data.component;
import org.springframework.integration.annotation.MessagingGateway;
import org.springframework.integration.mqtt.support.MqttHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;
@Component
@MessagingGateway(defaultRequestChannel = "mqttOutboundChannel")
public interface MqttGatewayComponent {
void sendToMqtt(String data);
void sendToMqtt(String payload, @Header(MqttHeaders.TOPIC) String topic);
void sendToMqtt(@Header(MqttHeaders.TOPIC) String topic, @Header(MqttHeaders.QOS) int qos, String payload);
}
发送数据到mqtt伪代码
@Autowired
private MqttGatewayComponent mqttGatewayComponent;
mqttGatewayComponent.sendToMqtt("json string", "data/abcd");
参考链接: https://blog.csdn.net/sinat_21184471/article/details/87186186 https://blog.csdn.net/qq_29467891/article/details/107043225?utm_source=app https://blog.csdn.net/myinsert/article/details/107715538
|