About spring boot integrated MQTT

installation

Speaking mqtt, first be sure to install, what's installation address: HTTP: //activemq.apache.org/ap ...
I was a local Windows environment, so installed the Windows version, this is the first note of place, because the use of the time behind some of the different windows and linux

After the download is complete extract the install, unzip into the bin directory under here after the completion of, or directly into their own use cmd to open a command window here also, and then run apollo.cmd create a service instance instance name is my command is so mybroker apollo.cmd create mybroker, this can easily specify your own name

After you create an instance of the bin directory found more than a folder, this folder is your instance name, running into the folder 
.apollo-broker.cmd run the command

This will launch a success

 

Success can start to HTTP: // localhost : 61680 / Console / index.html look, user name and password found in the input file mybrokeretcusers.properties can go

 

 

There are a number corresponding to the information on the page and subscribe to the theme of connection information, interested facie, it will be mentioned later

use

The next step is to use a successful installation, first create a maven project, the introduction of configuration

    <!--mqtt-->
    <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>

Because we subscribe later logs messages printed with the consumer in order to facilitate slf4j also introduced lombok configuration:

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
    </dependency>

After introducing complete we are ready to start using the mqtt
here for the convenience of maintenance and configuration I put some configuration parameters in the properties file inside:

#MQTT配置信息

spring.mqtt.username=admin

spring.mqtt.password=password

spring.mqtt.url=tcp://localhost:61613

spring.mqtt.client.id=clientId

spring.mqtt.server.id=serverId

spring.mqtt.default.topic=topic

Here I met a pit, specially annotated, is to subscribe to a subscription id and end id end dissemination of information dissemination of information must not be the same, this will lead to mqtt recognized as two of id, news out of it become disconnected, Subscribe to end always receive messages, the problem I find a good long do not know what the problem, it is easy to mistake the fourth year, the second question is mqtt server connection address, tcp under Windows and linux the port is not the same, the start of apollo logs can be seen

 

Listening tcp port 61613, to see a lot of demo are 1883 other people, if you have been Rom, probably because this

The next step is spring.mqtt.default.topic to configure, and this is mqtt subscriptions and push the message subject, since then the subject of a message you want to subscribe to the message and theme consistent dissemination of information in order to receive the message, and as rabbitmq

The client is then

@Configuration
@IntegrationComponentScan
@Slf4j
public class MqttSenderConfig {

    @Value("${spring.mqtt.username}")
    private String username;

    @Value("${spring.mqtt.password}")
    private String password;

    @Value("${spring.mqtt.url}")
    private String hostUrl;

    @Value("${spring.mqtt.client.id}")
    private String clientId;

    @Value("${spring.mqtt.default.topic}")
    private String defaultTopic;

    @Bean
    public MqttConnectOptions getMqttConnectOptions(){
        MqttConnectOptions mqttConnectOptions=new MqttConnectOptions();
        mqttConnectOptions.setUserName(username);
        mqttConnectOptions.setPassword(password.toCharArray());
        mqttConnectOptions.setServerURIs(new String[]{hostUrl});
        mqttConnectOptions.setKeepAliveInterval(2);
        return mqttConnectOptions;
    }

    @Bean
    public MqttPahoClientFactory mqttClientFactory() {
        DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
        factory.setConnectionOptions(getMqttConnectOptions());
        return factory;
    }

    @Bean
    @ServiceActivator(inputChannel = "mqttOutboundChannel")
    public MessageHandler mqttOutbound() {
        MqttPahoMessageHandler messageHandler =  new MqttPahoMessageHandler(clientId, mqttClientFactory());
        messageHandler.setAsync(true);
        messageHandler.setDefaultTopic(defaultTopic);
        return messageHandler;
    }

    @Bean
    public MessageChannel mqttOutboundChannel() {
        return new DirectChannel();
    }
  }  
  

Here is something wrong, if you were to copy my code words MessageHandler This class is no need to manually guide the package, read the source code found here need is a message processing handler is required to achieve org.springframework.messaging.MessageHandler directly import this package on the line

@Component
@MessagingGateway(defaultRequestChannel = "mqttOutboundChannel")
public interface MsgWriter {

    void sendToMqtt(String data);
    void sendToMqtt(String payload,@Header(MqttHeaders.TOPIC) String topic);
    void sendToMqtt(@Header(MqttHeaders.TOPIC) String topic, @Header(MqttHeaders.QOS) int qos, String payload);

}

This is the messaging interface, when you need to send a message directly call on the line, provides several overloaded methods or data payload is sending the message content
topic is the subject of the message is sent, where you can define your own flexible, you can also use the default theme is the theme of the configuration file, qos is mqtt several mechanisms for message processing into 0,1,2 where 0 represents the subscribers did not receive the message will not be sent again, the message will be lost, 1 indicates that attempts to re test, until the message is received, but that could lead to subscribers receive repeated messages, compared to more than a 2 to heavy action to ensure that there is a message subscribers receive
, of course, these three modes the performance is certainly not the same, qos = 0 is the best, the worst 2, are interested can go to learn more about this I will not repeat them

The above is complete to send a message, you can go to HTTP: // localhost : 61680 / Console / index.html look at the record of the message, here I wrote an interface method calls sendToMqtt send a message

 

 

You see receive two themes, I was two because I subscribe to two themes so shown above, I just posted a message's theme is too open so too will see the news served up

 

 

If you have not write subscribers if consumers are not now show me the seven messages, send proved successful

Then there is the subscriber, for convenience I will write directly on the startup class, and did not use all the configuration

@SpringBootApplication
@EnableAutoConfiguration
public class MytestApplication {

    public static void main(String[] args) {
        SpringApplication.run(MytestApplication.class, args);
    }


    @Value("${spring.mqtt.server.id}")
    private String serverId;

    @Bean
    public MqttPahoClientFactory mqttClientFactory() {
        DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
        factory.setServerURIs("tcp://localhost:61613");
        factory.setUserName("admin");
        factory.setPassword("password");
        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(serverId,
                mqttClientFactory(), "too");
        adapter.setCompletionTimeout(5000);
        adapter.setConverter(new DefaultPahoMessageConverter());
        adapter.setQos(1);
        return adapter;
    }

}

Here you can specify subscribed threads, I subscribe to the hair is just too theme, as well as id id of the sender and do not subscribe to the same party
to re-start the project, send a message, you will find the console has been printed out messages

On behalf of subscribers has successfully received the message, at the same time

 

 

Also displays the message subscriber and recording, so far a complete messaging and subscription is complete, relatively simple, but very inattentive prone to problems, hoping to help new people get started

Guess you like

Origin www.cnblogs.com/xuxiaobai13/p/11846865.html