您好,登錄后才能下訂單哦!
這篇文章給大家介紹使用springboot怎么結合mqtt進行開發,內容非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
MQTT(Message Queuing Telemetry Transport)是基于二進制消息的發布/訂閱編程模式的消息協議,非常適合需要低功耗和網絡帶寬有限的IoT場景。
maven
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-integration</artifactId> </dependency> <dependency> <groupId>org.springframework.integration</groupId> <artifactId>spring-integration-stream</artifactId> </dependency> <dependency> <groupId>org.springframework.integration</groupId> <artifactId>spring-integration-mqtt</artifactId> </dependency>
配置client factory
@Bean public MqttPahoClientFactory mqttClientFactory() { DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory(); factory.setServerURIs("tcp://demo:1883"); // factory.setUserName("guest"); // factory.setPassword("guest"); return factory; }
配置consumer
@Bean public IntegrationFlow mqttInFlow() { return IntegrationFlows.from(mqttInbound()) .transform(p -> p + ", received from MQTT") .handle(logger()) .get(); } private LoggingHandler logger() { LoggingHandler loggingHandler = new LoggingHandler("INFO"); loggingHandler.setLoggerName("siSample"); return loggingHandler; } @Bean public MessageProducerSupport mqttInbound() { MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter("siSampleConsumer", mqttClientFactory(), "siSampleTopic"); adapter.setCompletionTimeout(5000); adapter.setConverter(new DefaultPahoMessageConverter()); adapter.setQos(1); return adapter; }
配置producer
@Bean public IntegrationFlow mqttOutFlow() { //console input // return IntegrationFlows.from(CharacterStreamReadingMessageSource.stdin(), // e -> e.poller(Pollers.fixedDelay(1000))) // .transform(p -> p + " sent to MQTT") // .handle(mqttOutbound()) // .get(); return IntegrationFlows.from(outChannel()) .handle(mqttOutbound()) .get(); } @Bean public MessageChannel outChannel() { return new DirectChannel(); } @Bean public MessageHandler mqttOutbound() { MqttPahoMessageHandler messageHandler = new MqttPahoMessageHandler("siSamplePublisher", mqttClientFactory()); messageHandler.setAsync(true); messageHandler.setDefaultTopic("siSampleTopic"); return messageHandler; }
配置MessagingGateway
@MessagingGateway(defaultRequestChannel = "outChannel") public interface MsgWriter { void write(String note); }
關于使用springboot怎么結合mqtt進行開發就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。