Because the company is developing a background and Android update system recently, after repeated research, Mqtt is also the current popular framework. In order to make the project operate, ActiveMQ was finally chosen. But in the process, Apollo also turned out to be a pretty good server. Of course, the latter has been abandoned by APace, but today we will sort out the whole process of SpringBoot+MQTT+ Apollo to implement the subscription publishing function.


I won’t go into details about the prerequisites that the project will need first, such as how Apollo is downloaded and the MQTT test tool. If you really don’t know how to talk about Damon in private, you won’t waste your time here.

For the project, first you need to import the Maven package:

pom.xml

<! -- MQTT --> <dependency> <groupId>org.springframework.integration</groupId> <artifactId>spring-integration-stream</artifactId> </dependency> <dependency> <groupId>org.springframework.integration</groupId> <artifactId>spring-integration-mqtt</artifactId> </dependency>Copy the code

The goal is to use MQTT in project teams

The next step is to configure the project’s YML file using properties:

applicaiton.yml

(` ` `)

MQTT: username: admin password: password host-url: TCP ://127.0.0.1:8161 # Default topic: home/garden/fountain # Default theme timeout: 100 keepalive: 100 # Tomcat server: tomcat: uri-encoding: UTF-8 max-threads: 1000 min-spare-threads: 30 port: 8088Copy the code

(` ` `)

Notice host-URL, that’s your address for Apollo

Go to step 3, which is the files in the project:

MqttConfig file

@Component @ConfigurationProperties("mqtt") @Setter @Getter public class MqttConfig { @Autowired private MqttPushClient mqttPushClient; /** * username */ / @value ("username") private String username; /** * password */ private String password; /** * private String hostUrl; /** * clientID */ private String clientID; /** * default connection topic */ private String defaultTopic; /** * timeout */ private int timeout; /** ** private int keepalive; @Bean public MqttPushClient getMqttPushClient() { System.out.println("hostUrl: "+ hostUrl); System.out.println("clientID: "+ clientID); System.out.println("username: "+ username); System.out.println("password: "+ password); System.out.println("timeout: "+timeout); System.out.println("keepalive: "+ keepalive); mqttPushClient.connect(hostUrl, clientID, username, password, timeout, keepalive); Mqttpushclient. subscribe(defaultTopic, 0); return mqttPushClient; }}Copy the code
The purpose is to configure the corresponding message

The fourth step is publishing and subscribing:

MqttPushClient

@Component public class MqttPushClient { private static final Logger logger = LoggerFactory.getLogger(MqttPushClient.class); @Autowired private PushCallback pushCallback; private static MqttClient client; private static MqttClient getClient() { return client; } private static void setClient(MqttClient client) { MqttPushClient.client = client; } /** * client connection ** @param host IP + port * @param clientID clientID * @param username username * @param password password * @param timeout Timeout duration * @param Keepalive number */ public void connect(String host, String clientID, String username, String password, int timeout, int keepalive) { MqttClient client; try { client = new MqttClient(host, clientID, new MemoryPersistence()); MqttConnectOptions options = new MqttConnectOptions(); options.setCleanSession(true); options.setUserName(username); options.setPassword(password.toCharArray()); options.setConnectionTimeout(timeout); options.setKeepAliveInterval(keepalive); MqttPushClient.setClient(client); try { client.setCallback(pushCallback); client.connect(options); } catch (Exception e) { e.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); }} /** * Release ** @param qos connection * @param retained or not * @param topic * @param pushMessage body */ public void publish(int qos, boolean retained, String topic, String pushMessage) { MqttMessage message = new MqttMessage(); message.setQos(qos); message.setRetained(retained); message.setPayload(pushMessage.getBytes()); MqttTopic mTopic = MqttPushClient.getClient().getTopic(topic); if (null == mTopic) { logger.error("topic not exist"); } MqttDeliveryToken token; try { token = mTopic.publish(message); token.waitForCompletion(); } catch (MqttPersistenceException e) { e.printStackTrace(); } catch (MqttException e) { e.printStackTrace(); }} /** * subscribe to a topic ** @param topic * @param qos connection */ public void subscribe(String topic, Int qos) {logger.info(" Start subscribing to topic "+ topic); try { MqttPushClient.getClient().subscribe(topic, qos); } catch (MqttException e) { e.printStackTrace(); }}}Copy the code

Subscribe to topics and publish more

Finally, let’s take a test to see if our results are correct:

TestController

@RestController @RequestMapping("/") public class TestController { @Autowired private MqttPushClient mqttPushClient; @GetMapping(value = "/publishTopic") public String publishTopic() { String topicString = "home/garden/fountain"; Publish (0, false, topicString, "test the publish message "); mqttpushClient.publish (0, false, topicString," test the publish message "); return "ok"; @requestMapping ("/publishTopic/{data}") public String test1(@pathVariable ("data") String data) {public String test1(@pathVariable ("data") String data) { String topicString = "home/garden/fountain"; mqttPushClient.publish(0,false,topicString, data); return "ok"; } // Send custom message content, @requestMapping ("/publishTopic/{topic}/{data}") public String test2(@pathVariable ("topic") String topic, @PathVariable("data") String data) { mqttPushClient.publish(0,false,topic, data); return "ok"; }}Copy the code

That’s OK!

You can use MQtt.fx for testing. Send it with Postman and you can see the final result. Here, for the reason of time, I will not say more, there are any interesting problems, we can discuss together. Hopefully, Damon will keep us entertained by sharing interesting development stories. Next, choose from POI implementation export import or ActiveMQ.


The last sentence: far to the world surprised Hong Feast a glimpse of the world sheng Yan hard work, to the full stack forward!