preface

Recently, in order to prepare for the completion of the project, SpringBoot is used to build the MQTT back end. This paper mainly records the process of building SpringBoot MQTT multi-module project in IDEA

Development tools and system environment

  • IDE: IntelliJ IDEA 2020.2
  • Operating system: Windows 10 2004
  • Java Version: 1.8
  • SpringBoot Version: 2.1.17. RELEASE

Project path

Study | - Study - common public class # stored | - Study - mapper # # layer mapper | - Study - MQTT MQTT relevant configuration files and interface | - Study - service # The service layer | - study - serviceimpl # service implementation classes | | - study - web # web layer -- pom. XML 12345678Copy the code

The configuration process

1. Set up the parent project

  1. Create a SpringBoot project in IDEA

    Here I use ali cloud startup service, normal use can directly use the original startup service

  2. Select the Java version according to your requirements, initialize the type and configure groupID and artifactId, which I configured here as the reverse of my domain name, and define artifactId as Study. Click Next when the configuration is complete

  1. In this step, select the version of SpringBoot you want, I chose 2.1.17.RELEASE, and click NEXT. You do not need to check any dependencies in this step.

  1. Select a save path and click Finish to complete the creation.

  1. Delete unnecessary files. Put the directory undersrc/.HELP.md.mvnw.mvnw.cmdWait for all files to be deleted (excluding.gitigore)

At this point, the parent project level has been created and the final project directory is as follows:

2. Build sub-projects

  1. Right-click project root -> New -> New module

  1. Select Maven and click Next

  1. Configure the parent item, project name, and build coordinates, and click Finish. Take the study-common module as an example

  1. This analogy creates the entire project, with the project directory shown in the figure below

At this point, we have built all the sub-projects and then started to configure the POM files for each project

3. Configure each module

1. Configure the parent project

  • Configure the pom.xml file for the parent project

    The parent project’s POM. XML is a constraint on child project references. The parent project’s pom. XML uses dependencyManagement to constrain the versions of dependencies in the child project. In the parent project, you can refer to references that are used by all the child projects. The parent project’s POM.xml file is as follows:

    <? The XML version = "1.0" encoding = "utf-8"? > < project XMLNS = "http://maven.apache.org/POM/4.0.0" XMLNS: xsi = "http://www.w3.org/2001/XMLSchema-instance" Xsi: schemaLocation = "http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd" > The < modelVersion > 4.0.0 < / modelVersion > < groupId > com. Itbu < / groupId > < artifactId > study < / artifactId > < packaging > pom < / packaging > < version > 1.0.0 < / version > < modules > < module > study - common < module > < module > study - service < / module > <module>study-serviceimpl</module> <module>study-web</module> <module>study-mapper</module> <module>study-mqtt</module> </modules> <name>study</name> <description>Demo project for Spring Boot</description> <parent> <artifactId>spring-boot-starter-parent</artifactId> <groupId>org.springframework.boot</groupId> <version>2.1.17.RELEASE</version> <relativePath/> </parent> <properties> <java.version>1.8</java.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> < spring - the boot version > 2.1.17. RELEASE < / spring - the boot. Version > < mybatis boot. Starter. Version > 2.1.4 < / mybatis. Boot. Starter. Version > < mysql. Connector. Java version > 8.0.22 < / mysql. Connector. Java version > < druid. Version > 1.2.0 < / druid version > < integration version > 2.3.7. RELEASE < / integration version > < stream. Integration. Version > 5.4.2 < / stream. Integration. Version > < MQTT. Integration. Version > 5.4.2 < / MQTT. Integration. Version > < / properties > < dependencies > < the dependency > <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> <version>${spring-boot.version}</version> <type>pom</type> <scope>import</scope> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>${mybatis.boot.starter.version}</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.connector.java.version}</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>${druid.version}</version> </dependency> </dependencies> </dependencyManagement> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <version>2.1.17.RELEASE</version> </plugin> </plugins> </build> </project> 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646 566676869707172737475767778798081828384858687888990919293949596979899100101102Copy the code

2. Configure the Common module

  • Configure the POM.xml file

    The common module mainly contains some common classes and interfaces, but only need to configure the parent item to point to the parent project. The common module’s POM.xml configuration file is as follows:

    <? The XML version = "1.0" encoding = "utf-8"? > < project XMLNS = "http://maven.apache.org/POM/4.0.0" XMLNS: xsi = "http://www.w3.org/2001/XMLSchema-instance" Xsi: schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" > < the parent > < artifactId > study < / artifactId > < groupId > com. Itbu < / groupId > < version > 1.0.0 < / version > < / parent > < the groupId > com. Itbu. Study < / groupId > < artifactId > common < / artifactId > < version > 1.0.0 < / version > < modelVersion > 4.0.0 < / modelVersion > < packaging > jar < / packaging > < properties > < Java version > 1.8 < / Java version > </properties> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> 1234567891011121314151617181920212223242526Copy the code
  • Create the required classes and interfaces

    After configuring POM.xml, you can create the required classes and interfaces in the directory. In this project, I created UserBean as poJO class and JsonResult class as JSON return result as general class respectively. The project structure is as follows:

    study-common
    	|----pom.xml
    	|----src
    		|----test
    		|----main
    			|----resources
    			|----java
    				|----com.itbu.study.common
    					|----bean
    						|----UserBean.java
    					|----result
    						|----JsonResult.java
    123456789101112
    Copy the code

    The UserBean. Java file

    package com.itbu.study.common.bean; public class UserBean { private int id; private String username; private String password; public int getId() { return id; } public String getPassword() { return password; } public String getUsername() { return username; } public void setPassword(String password) { this.password = password; } public void setId(int id) { this.id = id; } public void setUsername(String username) { this.username = username; } public UserBean(){ } public UserBean(String username, String password){ this.username = username; this.password = password; }} 12345678910111213141516171819202122232425262728293031323334353637383940Copy the code

    JsonResult. Java file

    package com.itbu.study.common.result; public class JsonResult<T> { private int code; private String msg; private T data; public JsonResult(int Code,String msg){ this.code = Code; this.msg = msg; } public JsonResult(T data) { this.data = data; this.code = 0; This. MSG = "Operation successful!" ; } public JsonResult(T data, String msg) { this.data = data; this.code = 0; this.msg = msg; } public String getMsg() { return msg; } public int getCode() { return code; } public T getData() { return data; } public void setData(T data) { this.data = data; } public void setMsg(String msg) { this.msg = msg; } public void setCode(int code) { this.code = code; }} 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748Copy the code

3. Configure mapper

Mapper module corresponds to the MAPper layer, also known as the DAO layer, used for communication with the database, read and write operations. The persistence layer framework we use here is Mybatis and the connected database is mysql database. You also need the various POJO classes in the Common module, where you need to introduce the various references. The operation steps are as follows:

  • Configure the POM.xml file

    Mysql/Mybatis/Druid/mysql.mysql/mybatis/Druid/mysql.mysql

    <? The XML version = "1.0" encoding = "utf-8"? > < project XMLNS = "http://maven.apache.org/POM/4.0.0" XMLNS: xsi = "http://www.w3.org/2001/XMLSchema-instance" Xsi: schemaLocation = "http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd" > < modelVersion > 4.0.0 < / modelVersion > < groupId > com. Itbu. Study < / groupId > < artifactId > mapper < / artifactId > <version>1.0.0</version> <name>mapper</name> <description>Demo project for Spring Boot</description> <packaging>jar</packaging> <parent> <artifactId>study</artifactId> <groupId>com.itbu</groupId> <version>1.0.0</version> <relativePath>.. / pom. XML < / relativePath > < / parent > < properties > < Java version > 1.8 < / Java version > <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> < spring - the boot version > 2.1.17. RELEASE < / spring - the boot. Version > < / properties > < dependencies > <! Study </groupId> <artifactId>common</artifactId> <version>1.0.0</version> </dependency> <! Alibaba </groupId> <artifactId>druid</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859Copy the code
  • Write interface and mapping files

    As with module-free operations, create a mapper directory under the Resource folder and write an XML file for the mapping. At the same time, create corresponding interfaces. The project catalog is roughly as follows:

    study-mapper
    	|----pom.xml
    	|----src
    		|----test
    		|----main
    			|----java
    				|----com.itbu.study.mapper
    					|----UserMapper.java
    			|----resources
    				|----mapper
    					|----UserMapper.xml
    1234567891011
    Copy the code

    UserMapper. Java file

    package com.itbu.study.mapper;
    import com.itbu.study.common.bean.UserBean;
    import java.util.List;
    public interface UserMapper {
        List<UserBean> getAll();
    }
    123456
    Copy the code

    UserMapper.xml

    <? The XML version = "1.0" encoding = "utf-8"? > <! DOCTYPE mapper PUBLIC "- / / mybatis.org//DTD mapper / 3.0 / EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > < mapper namespace="com.itbu.study.mapper.UserMapper"> <select id="getAll" resultType="com.itbu.study.common.bean.UserBean"> select * from mqtt.user_table </select> </mapper> 1234567Copy the code

Configure the Service module

Service module is also the Service layer, mainly some service interface to facilitate the call to the controller layer. The steps are as follows:

  • Configure the POM.xml file

    The Service layer needs to use the POJO class in the Common module, where you need to add dependencies to the module

    <? The XML version = "1.0" encoding = "utf-8"? > < project XMLNS = "http://maven.apache.org/POM/4.0.0" XMLNS: xsi = "http://www.w3.org/2001/XMLSchema-instance" Xsi: schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" > < the parent > < artifactId > study < / artifactId > < groupId > com. Itbu < / groupId > < version > 1.0.0 < / version > < relativePath >). / pom. XML < / relativePath > < / parent > < modelVersion > 4.0.0 < / modelVersion > < groupId > com. Itbu. Study < / groupId > <artifactId>service</artifactId> <version>1.0.0</version> <packaging>jar</packaging> <name>service</name> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>com.itbu.study</groupId> <artifactId>common</artifactId> <version>1.0.0</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> 1234567891011121314151617181920212223242526272829303132333435363738Copy the code
  • Write service interfaces

    The interface here is similar to the Mapper layer, so I’m not going to go into detail here, but I’m going to put the code directly here

    UserService.java

    package com.itbu.study.service;
    
    import com.itbu.study.common.bean.UserBean;
    
    import java.util.List;
    
    public interface UserService {
        List<UserBean> getAll();
    }
    
    12345678910
    Copy the code

5. Configure the ServiceImpl module

Serviceimpl is the implementation class of the Service interface. The implementation steps are as follows:

  • Configure the POM.xml file

    Serviceimpl requires support from the Mapper layer, implements the various interfaces of the Service layer, and references to the POJO classes in the Common module, which we add directly

    <? The XML version = "1.0" encoding = "utf-8"? > < project XMLNS = "http://maven.apache.org/POM/4.0.0" XMLNS: xsi = "http://www.w3.org/2001/XMLSchema-instance" Xsi: schemaLocation = "http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd" > < modelVersion > 4.0.0 < / modelVersion > < groupId > com. Itbu. Study < / groupId > < artifactId > serviceimpl < / artifactId > <version>1.0.0</version> <name> ServiceImpl </name> <description>Demo project for Spring Boot</description> <packaging>jar</packaging> <parent> <artifactId>study</artifactId> <groupId>com.itbu</groupId> <version>1.0.0</version> < / parent > < properties > < Java version > 1.8 < / Java version > <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> < spring - the boot version > 2.1.17. RELEASE < / spring - the boot. Version > < / properties > < dependencies > < the dependency > <groupId>com.itbu.study</groupId> <artifactId>common</artifactId> <version>1.0.0</version> </dependency> <dependency> <groupId>com.itbu.study</groupId> <artifactId>service</artifactId> <version>1.0.0</version> </dependency> <dependency> <groupId>com.itbu.study</groupId> <artifactId>mapper</artifactId> <version>1.0.0</version> </dependency> </dependencies>  <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849Copy the code
  • Write implementation classes based on service interfaces

    Userserviceimp.java note the @service annotation on the implementation class for SpringBoot framework recognition

    package com.itbu.study.serviceimpl; import com.itbu.study.common.bean.UserBean; import com.itbu.study.mapper.UserMapper; import com.itbu.study.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public List<UserBean> getAll() { return userMapper.getAll(); }} 1234567891011121314151617181920Copy the code

6. Configure the Web module

Now comes the core, which is the part that is quite different from the non-modular configuration. You need to configure the startup class and configuration file on the Web layer. The configuration procedure is as follows:

  • Configure the POM.xml file

    The Web layer will directly reference the various interfaces of the Service layer, the various classes of the Common module, and here we add the dependencies directly

    <? The XML version = "1.0" encoding = "utf-8"? > < project XMLNS = "http://maven.apache.org/POM/4.0.0" XMLNS: xsi = "http://www.w3.org/2001/XMLSchema-instance" Xsi: schemaLocation = "http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd" > < modelVersion > 4.0.0 < / modelVersion > < groupId > com. Itbu. Study < / groupId > < artifactId > serviceimpl < / artifactId > <version>1.0.0</version> <name> ServiceImpl </name> <description>Demo project for Spring Boot</description> <packaging>jar</packaging> <parent> <artifactId>study</artifactId> <groupId>com.itbu</groupId> <version>1.0.0</version> < / parent > < properties > < Java version > 1.8 < / Java version > <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> < spring - the boot version > 2.1.17. RELEASE < / spring - the boot. Version > < / properties > < dependencies > < the dependency > <groupId>com.itbu.study</groupId> <artifactId>common</artifactId> <version>1.0.0</version> </dependency> <dependency> <groupId>com.itbu.study</groupId> <artifactId>service</artifactId> <version>1.0.0</version> </dependency> <dependency> <groupId>com.itbu.study</groupId> <artifactId>mapper</artifactId> <version>1.0.0</version> </dependency> </dependencies>  <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950Copy the code
  • Write individual controllers and configuration files

    Create the corresponding file according to the following project structure:

    Study - web | - pom. XML | -- -- SRC | - test Java | -- - | -- com. Itbu. Study. The web | -- WebApplicationTests. Java # test class | - main  |----java |----com.itbu.study.web |----WebApplication.java |----controller |----ApiController.java |----resources |----config |----application.yml |----application-dev.yml 1234567891011121314151617Copy the code

    Write the startup class, remember to add MapperScan

    WebApplication.java

    package com.itbu.study.web; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication(scanBasePackages = {"com.itbu.study.*"}) @MapperScan("com.itbu.study.mapper") public class WebApplication { public static void main(String[] args) { SpringApplication.run(WebApplication.class, args); }} 1234567891011Copy the code

    Writing the Controller layer

    ApiController.java

    package com.itbu.study.web.controller; import com.itbu.study.common.bean.UserBean; import com.itbu.study.common.result.JsonResult; import com.itbu.study.service.UserService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import javax.xml.ws.RequestWrapper; import java.util.List; @RestController @RequestMapping("/api") public class ApiController { private final Logger logger = LoggerFactory.getLogger(this.getClass()); public ApiController(UserService userService){ this.userService = userService; } private final UserService userService; @RequestMapping("/index") public List<UserBean> index(){ return userService.getAll(); }} 12345678910111213141516171819202122232425262728Copy the code

    In the configuration file, set the data source and mapper mapping file and the listening port

    application-dev.xml

    Mybatis: mapper-locations: classpath*:mapper/*.xml # The root password: 123456 url: JDBC: mysql: / / 192.168.28.88:10090 / MQTT? useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC driver-class-name: com.mysql.cj.jdbc.Driver 12345678910Copy the code

7. Test

Now that we’ve configured a multi-module MQTT back-end base project, we’re ready for a simple test

Run the project and enter http://localhost:10000/api/index in your browser, returned the following results show that the test successfully

4. Configure the MQTT

Now that we have completed the configuration of the SpringBoot base project, we will make MQTT into a module as follows:

  • Configure the POM.xml file

    We mainly use the spring-integration-MQTT jar package to integrate MQTT functionality, so we add the dependency to this package in POM. The pom. XML file is as follows:

    <? The XML version = "1.0" encoding = "utf-8"? > < project XMLNS = "http://maven.apache.org/POM/4.0.0" XMLNS: xsi = "http://www.w3.org/2001/XMLSchema-instance" Xsi: schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" > < the parent > < artifactId > study < / artifactId > < groupId > com. Itbu < / groupId > < version > 1.0.0 < / version > < / parent > < modelVersion > 4.0.0 < / modelVersion > < groupId > com. Itbu. Study < / groupId > < artifactId > MQTT < / artifactId > <packaging>jar</packaging> <properties> <java.version>1.8</java.version> </properties> <dependencies> <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> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> 1234567891011121314151617181920212223242526272829303132333435363738394041424344Copy the code
  • Add the following configuration to the study-web configuration file:

    MQTT: enabled: true username: root password: 123456 url: TCP: / / 192.168.28.88:15005 producer: clientId: server defaultTopic: default consumer: clientId: client defaultTopic: default 1234567891011Copy the code
  • Write MQTT configuration classes and methods

    The project structure is as follows:

    study-mqtt
    	|----pom.xml
    	|----src
    		|----test
    		|----main
    			|----resources
    			|----java
    				|----com.itbu.study.mqtt
    					|----MqttBaseConfig.java
    					|----MqttInConfig.java
    					|----MqttOutConfig.java
    					|----MqttMessageReceiver.java
    					|----MqttMessageSender.java
    12345678910111213
    Copy the code

    MqttBaseConfig.java

    package com.itbu.study.mqtt; import org.eclipse.paho.client.mqttv3.MqttConnectOptions; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory; import org.springframework.integration.mqtt.core.MqttPahoClientFactory; @Configuration @ConditionalOnProperty(value = "mqtt.enabled", havingValue = "true") public class MqttBaseConfig { @Value("${mqtt.url:#{null}}") private String[] url; @Value("${mqtt.username:}") private String username; @Value("${mqtt.password:}") private String password; @Bean public MqttPahoClientFactory factory(){ DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();  MqttConnectOptions options = new MqttConnectOptions(); if(username ! = null) options.setUserName(username); if(password ! = null) options.setPassword(password.toCharArray()); options.setServerURIs(url); factory.setConnectionOptions(options); return factory; }} 1234567891011121314151617181920212223242526272829303132333435Copy the code

    MqttInConfig.java

    package com.itbu.study.mqtt; import com.itbu.study.mqtt.MqttMessageReceiver; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.integration.annotation.ServiceActivator; import org.springframework.integration.channel.DirectChannel; import org.springframework.integration.core.MessageProducer; import org.springframework.integration.mqtt.core.MqttPahoClientFactory; import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter; import org.springframework.integration.mqtt.support.DefaultPahoMessageConverter; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.MessageHandler; @Configuration @ConditionalOnProperty(value = "mqtt.enabled", havingValue = "true") public class MqttInConfig { private final MqttMessageReceiver mqttMessageReceiver; public MqttInConfig(MqttMessageReceiver mqttMessageReceiver){ this.mqttMessageReceiver = mqttMessageReceiver; } @Value("${mqtt.producer.clientId:") private String clientId; @Value("${mqtt.producer.defaultTopic}") private String topic; @Bean public MessageChannel mqttInputChannel(){ return new DirectChannel(); } @Bean public MessageProducer channelInbound(MessageChannel mqttInputChannel, MqttPahoClientFactory factory){ MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter(clientId, factory, topic); adapter.setCompletionTimeout(5000); adapter.setConverter(new DefaultPahoMessageConverter()); adapter.setQos(2); adapter.setOutputChannel(mqttInputChannel); return adapter; } @Bean @ServiceActivator(inputChannel = "mqttInputChannel") public MessageHandler mqttMessageHandler(){ return this.mqttMessageReceiver; }} 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354Copy the code

    MqttOutConfig.java

    package com.itbu.study.mqtt; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.integration.annotation.ServiceActivator; import org.springframework.integration.channel.DirectChannel; import org.springframework.integration.mqtt.core.MqttPahoClientFactory; import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.MessageHandler; @Configuration @ConditionalOnProperty(value = "mqtt.enabled", havingValue = "true") public class MqttOutConfig { @Value("${mqtt.consumer.clientId:}") private String clientId; @Value("${mqtt.consumer.defaultTopic}") private String topic; @Bean public MessageChannel mqttOutputChannel(){ return new DirectChannel(); } @Bean @ServiceActivator(inputChannel = "mqttOutputChannel") public MessageHandler mqttOutBound(MqttPahoClientFactory factory){ MqttPahoMessageHandler messageHandler = new MqttPahoMessageHandler(clientId, factory); messageHandler.setAsync(true); messageHandler.setDefaultQos(2); messageHandler.setDefaultTopic(topic); return messageHandler; }} 12345678910111213141516171819202122232425262728293031323334353637Copy the code

    MqttMessageReceiver.java

    package com.itbu.study.mqtt; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.ComponentScan; import org.springframework.integration.mqtt.support.MqttHeaders; import org.springframework.messaging.Message; import org.springframework.messaging.MessageHandler; import org.springframework.messaging.MessagingException; import org.springframework.stereotype.Component; @Component @ConditionalOnProperty(value = "mqtt.enabled",havingValue = "true") public class MqttMessageReceiver implements MessageHandler { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Override public void handleMessage(Message<? > message) throws MessagingException { String topic = String.valueOf(message.getHeaders().get(MqttHeaders.RECEIVED_TOPIC)); String payload = String.valueOf(message.getPayload()); Logger. info(" received MQTT message, topic :{} message :{}", topic, payload); }} 12345678910111213141516171819202122232425Copy the code

    MqttMessageSender.java

    package com.itbu.study.mqtt;
    
    import org.springframework.integration.annotation.MessagingGateway;
    import org.springframework.integration.mqtt.support.MqttHeaders;
    import org.springframework.messaging.handler.annotation.Header;
    import org.springframework.stereotype.Component;
    
    @MessagingGateway(defaultRequestChannel = "mqttOutputChannel")
    @Component
    public interface MqttMessageSender {
        void sendToMqtt(String data);
        void sendToMqtt(@Header(MqttHeaders.TOPIC) String topic, String payload);
        void sendToMqtt(@Header(MqttHeaders.TOPIC) String topic, @Header(MqttHeaders.QOS) int qos, String payload);
    }
    
    123456789101112131415
    Copy the code
  • Add the @IntegrationComponentScan annotation to the bootstrap class

    package com.itbu.study.web; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.integration.annotation.IntegrationComponentScan; @SpringBootApplication(scanBasePackages = {"com.itbu.study.*","com.itbu.study.mqtt"}) @mapperscan ("com.itbu.study. Mapper ") @IntegrationComponentScan(basePackages = "com.itbu.study. MQTT ") Public static void main(String[] args) {public static void main(String[] args) { SpringApplication.run(WebApplication.class, args); }} 1234567891011121314151617Copy the code
  • Write the corresponding Controller, which I’m going to modify directly on ApiController

    package com.itbu.study.web.controller; import com.itbu.study.common.bean.UserBean; import com.itbu.study.common.result.JsonResult; import com.itbu.study.mqtt.MqttMessageSender; import com.itbu.study.service.UserService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import javax.xml.ws.RequestWrapper; import java.util.List; @RestController @RequestMapping("/api") public class ApiController { private final Logger logger = LoggerFactory.getLogger(this.getClass()); private final MqttMessageSender mqttMessageSender; public ApiController(MqttMessageSender mqttMessageSender, UserService userService){ this.mqttMessageSender = mqttMessageSender; this.userService = userService; } private final UserService userService; @RequestMapping("/index") public List<UserBean> index(){ return userService.getAll(); } @RequestMapping("/mqtt") public JsonResult<? > mqtt_sender(@RequestParam("msg")String msg){ logger.info("Send mqtt msg: {}", msg); mqttMessageSender.sendToMqtt(msg); logger.info("Send successfully!" ); return new JsonResult<>(0,"Send Successfully"); }} 12345678910111213141516171819202122232425262728293031323334353637383940414243444546Copy the code
  • test

    First we run the back-end project and you can see the following output from the log indicating that the back-end project started normally

We then use the mqtt.fx software to send helloWorld to the subscription theme Default

If the following information is displayed, the input channel is normal:

Then we enter http://localhost:10000/api/mqtt? in your browser MSG =1234556 and press Enter. The browser displays:

The following information is displayed in the log:

Since we subscribe to the theme of default, we also received the message sent by the producer. We open mqtt.fx and subscribe to the theme of default, and we can receive the following message:

Finally, welcome to pay attention to my public account: Java programmers gathering place, Maidong will share Java related technical articles or industry information every day, welcome to pay attention to and forward the article!