1. Spring Integration 集成 MQTT
1.1. 版本说明
构件 |
版本 |
spring-boot |
2.7.18 |
spring-boot-starter-integration |
2.7.18 |
spring-integration-mqtt |
5.5.20 |
1.2. 概览
1.3. 定义常量
| public static final String[] SERVER_URIS = { "tcp://localhost:1883" }; |
| public static final String USERNAME = "user1"; |
| public static final char[] PASSWORD = "123456".toCharArray(); |
| public static final String PUBLISHER_CLIENT_ID = "publisher"; |
| public static final String CONSUMER_CLIENT_ID = "consumer"; |
| public static final String TOPIC_1 = "topic-1"; |
| public static final String TOPIC_2 = "topic-2"; |
1.4. 定义 MqttClient 工厂
| @Bean |
| public MqttPahoClientFactory mqttClientFactory() { |
| DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory(); |
| MqttConnectOptions options = new MqttConnectOptions(); |
| options.setServerURIs(new String[]{ "tcp://localhost:1883" }); |
| options.setUserName("username"); |
| options.setPassword("password".toCharArray()); |
| options.setMaxInflight(5000); |
| options.setCleanSession(true); |
| options.setAutomaticReconnect(true); |
| factory.setConnectionOptions(options); |
| return factory; |
| } |
1.5. 消息入站
1.5.1. 定义 Message Channel
| @Bean |
| public DirectChannelSpec inboundMessageChannel1() { |
| return MessageChannels.direct(); |
| } |
| |
| @Bean |
| public DirectChannelSpec inboundMessageChannel2() { |
| return MessageChannels.direct(); |
| } |
1.5.2. 定义 Service Activator
| @Bean |
| @ServiceActivator(inputChannel = "inboundMessageChannel1") |
| public MessageHandler inboundMessageHandler1() { |
| return message -> log.info("received a message, topic: {}, qos: {}, payload: {}", message.getHeaders().get(RECEIVED_TOPIC), message.getHeaders().get(RECEIVED_QOS), message.getPayload()); |
| } |
| |
| @Bean |
| @ServiceActivator(inputChannel = "inboundMessageChannel2") |
| public MessageHandler inboundMessageHandler2() { |
| return message -> log.info("received a message, topic: {}, qos: {}, payload: {}", message.getHeaders().get(RECEIVED_TOPIC), message.getHeaders().get(RECEIVED_QOS), message.getPayload()); |
| } |
1.5.3. 定义 Message Router
| @Bean |
| public HeaderValueRouter inboundMessageRouter() { |
| HeaderValueRouter router = new HeaderValueRouter(RECEIVED_TOPIC); |
| router.setChannelMapping(TOPIC_1, "inboundMessageChannel1"); |
| router.setChannelMapping(TOPIC_2, "inboundMessageChannel2"); |
| return router; |
| } |
1.5.4. 定义 Message Producer
| @Bean |
| public MessageProducerSupport inboundMessageProducer() { |
| MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter(CONSUMER_CLIENT_ID, mqttClientFactory()); |
| adapter.addTopics(new String[]{TOPIC_1, TOPIC_2}, new int[]{0, 0}); |
| adapter.setCompletionTimeout(10_000); |
| adapter.setConverter(new DefaultPahoMessageConverter()); |
| return adapter; |
| } |
1.5.5. 基于 Java DSL 定义 Inbound Channel Adapter
| @Bean |
| public IntegrationFlow inboundIntegrationFlow() { |
| return IntegrationFlows.from(inboundMessageProducer()) |
| .route(inboundMessageRouter()) |
| .get(); |
| } |
1.6. 消息出站
1.6.1. 定义 Message Channel
| @Bean |
| public DirectChannelSpec outboundMessageChannel() { |
| return MessageChannels.direct(); |
| } |
1.6.2. 定义 Message Handler
| @Bean |
| public MessageHandler outboundMessageHandler() { |
| MqttPahoMessageHandler messageHandler = new MqttPahoMessageHandler(PUBLISHER_CLIENT_ID, mqttClientFactory()); |
| messageHandler.setAsync(true); |
| return messageHandler; |
| } |
1.6.3. 基于 Java DSL 定义 Outbound Channel Adapter
| @Bean |
| public IntegrationFlow outboundIntegrationFlow() { |
| return IntegrationFlows.from(outboundMessageChannel()) |
| .handle(outboundMessageHandler()) |
| .get(); |
| } |
1.6.4. 定义 Messaging Gateway
| @MessagingGateway(defaultRequestChannel = "outboundMessageChannel") |
| public interface MqttGateway { |
| void sendToMqtt(@Header(TOPIC) String topic, @Header(QOS) int qos, @Payload String payload); |
| } |
1.7. 测试
| @Component |
| @Slf4j |
| public class SpringIntegrationMqttDemo implements ApplicationRunner { |
| |
| @Resource |
| private MqttConfiguration.MqttGateway mqttGateway; |
| |
| @Override |
| public void run(ApplicationArguments args) throws Exception { |
| String payload1 = "hello, topic 1"; |
| mqttGateway.sendToMqtt(TOPIC_1, 0, payload1); |
| log.info("send a message, topic: {}, qos: 0, payload: {}", TOPIC_1, payload1); |
| |
| String payload2 = "hello, topic 2"; |
| mqttGateway.sendToMqtt(TOPIC_2, 0, payload2); |
| log.info("send a message, topic: {}, qos: 0, payload: {}", TOPIC_2, payload2); |
| } |
| } |
启动程序,控制台将输出:
| send a message, exchange: spring-integratiton-amqp-demo-exchange, routing key: routing-key-1, payload: hello, queue 1 |
| send a message, exchange: spring-integratiton-amqp-demo-exchange, routing key: routing-key-2, payload: hello, queue 2 |
| queue 2 received a message: GenericMessage [payload=hello, queue 2, headers={amqp_receivedDeliveryMode=PERSISTENT, amqp_receivedExchange=spring-integratiton-amqp-demo-exchange, amqp_deliveryTag=1, amqp_consumerQueue=spring-integratiton-amqp-demo-queue-2, amqp_redelivered=false, amqp_receivedRoutingKey=routing-key-2, replyChannel=nullChannel, amqp_contentEncoding=UTF-8, amqp_timestamp=Mon Sep 23 15:03:21 CST 2024, amqp_messageId=d524592f-a483-943d-d6ed-e1dfb6dc1f07, id=e6d1d2b2-ebb9-bd9c-62eb-65ce13d2e6e9, amqp_consumerTag=amq.ctag-Y157TiDiKLQei_-_mjk9Dw, contentType=text/plain, timestamp=1727075001386}] |
| queue 1 received a message: GenericMessage [payload=hello, queue 1, headers={amqp_receivedDeliveryMode=PERSISTENT, amqp_receivedExchange=spring-integratiton-amqp-demo-exchange, amqp_deliveryTag=1, amqp_consumerQueue=spring-integratiton-amqp-demo-queue-1, amqp_redelivered=false, amqp_receivedRoutingKey=routing-key-1, replyChannel=nullChannel, amqp_contentEncoding=UTF-8, amqp_timestamp=Mon Sep 23 15:03:21 CST 2024, amqp_messageId=fdff4ffb-8c73-9ac0-7bba-ae4055ace969, id=1ccf9615-4cb6-a9bc-a57c-102a4eed77b1, amqp_consumerTag=amq.ctag-Te7ucInXRmWdeQ4e_aPwLw, contentType=text/plain, timestamp=1727075001386}] |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)