-1

How to integrate a mqtt broker into spring boot project ?

I had ever tried spring-boot-starter-activemq , but it is a client ,not a broker


the main purpose is bridge message between cloud mqtt broker and Intranet Mqtt broker , include message bridging and topic management

Kscorpio
  • 1
  • 1
  • 3
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Jan 05 '22 at 11:16

1 Answers1

0

Messaging Broker server is independent, so Spring boot not provide implementation of mqtt broker, only using messaging broker client with spring boot you can connect with your MQTT broker like Mosqitto/VerneMq/RabbitMq etc.

Based on your message broker you can pick directly pick broker specific client library or you can use spring-integration-mqtt module

 <dependency>
            <groupId>org.springframework.integration</groupId>
            <artifactId>spring-integration-stream</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.integration</groupId>
            <artifactId>spring-integration-mqtt</artifactId>
        </dependency>

You can configure inbound or outbound implementation using spring integration module based on your requirement, it will give u flexibility so you can switch from one mqtt broker to another.

Inbond example:

@SpringBootApplication
public class MqttJavaApplication {

    public static void main(String[] args) {
        new SpringApplicationBuilder(MqttJavaApplication.class)
            .web(false)
            .run(args);
    }

    @Bean
    public IntegrationFlow mqttInbound() {
        return IntegrationFlows.from(
                         new MqttPahoMessageDrivenChannelAdapter("tcp://localhost:1883",
                                        "testClient", "topic1", "topic2");)
                .handle(m -> System.out.println(m.getPayload()))
                .get();
    }

}

Outbond example:

@SpringBootApplication
public class MqttJavaApplication {

    public static void main(String[] args) {
        new SpringApplicationBuilder(MqttJavaApplication.class)
            .web(false)
            .run(args);
    }

    @Bean
    public IntegrationFlow mqttOutboundFlow() {
        return f -> f.handle(new MqttPahoMessageHandler("tcp://host1:1883", "someMqttClient"));
    }

}

You can go through with spring boot integration-mqtt module docs for more details.

Bhushan Uniyal
  • 5,575
  • 2
  • 22
  • 45