Spring Integration 集成 MQTT
- 1. Spring Integration 集成 MQTT
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. 概览
flowchart TB
subgraph outBound["Out Bound"]
direction TB
AmqpGateway["MessagingGateway\n(mqttGateway)"]
--> outboundMessageChannel["MessageChannel\n(outboundMessageChannel)"]
--> MqttPahoMessageHandler["MessageHandler\n(MqttPahoMessageHandler)"]
end
subgraph emqx["EMQX"]
direction TB
topic1["topic-1"]
topic2["topic-2"]
end
subgraph inBound["In Bound"]
MqttPahoMessageDrivenChannelAdapter["MessageProducer\n(MqttPahoMessageDrivenChannelAdapter)"]
--> inboundMessageRouter["MessageRouter\n(inboundMessageRouter)"]
--"topic-1"--> inboundMessageChannel1["MessageChannel\n(inboundMessageChannel1)"]
--> inboundMessageHandler1["MessageHandler\n(inboundMessageHandler1)"]
inboundMessageRouter --"topic-2"--> inboundMessageChannel2["MessageChannel\n(inboundMessageChannel2)"]
--> inboundMessageHandler2["MessageHandler\n(inboundMessageHandler2)"]
end
MqttPahoMessageHandler --> topic1 --> MqttPahoMessageDrivenChannelAdapter
MqttPahoMessageHandler --> topic2 --> MqttPahoMessageDrivenChannelAdapter
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}]
本文来自博客园,作者:Jason,转载请注明原文链接:https://www.cnblogs.com/jason207010/p/18405933
浙公网安备 33010602011771号