这篇文章给大家介绍使用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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。