rabbitmq mqtt spring 发布订阅消息

1.rabbitmq 开启mqtt插件

rabbitmq-plugins enable rabbitmq_mqtt

2.新建maven工程,现价pom依赖(本工程是mqtt组件,不单独起服务,使用时引入即可)

<?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">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.hjjn</groupId>
    <artifactId>hj-mqtt</artifactId>
    <version>1.0-SNAPSHOT</version>

    <name>hj-mqtt</name>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.integration</groupId>
            <artifactId>spring-integration-mqtt</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
        </dependency>
    </dependencies>
</project>

3. 属性类

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * @author 123
 */
@ConfigurationProperties(prefix = "mqtt")
@Component
public class MqttProperties {

    private String host;

    private String username;

    private String password;

    private String[] topics;

    private String clientId = "";

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String[] getTopics() {
        return topics;
    }

    public void setTopics(String[] topics) {
        this.topics = topics;
    }

    public String getClientId() {
        return clientId;
    }

    public void setClientId(String clientId) {
        this.clientId = clientId;
    }

}

 

4.配置类

import org.eclipse.paho.client.mqttv3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @author 123
 */
@Configuration
public class MqttConfig {
    private static final Logger logger = LoggerFactory.getLogger(MqttConfig.class);

    @Bean
    public MqttConnectOptions mqttConnectOptions(MqttProperties mqttProperties) {
        MqttConnectOptions options = new MqttConnectOptions();
        options.setCleanSession(false);
        options.setConnectionTimeout(30);
        options.setKeepAliveInterval(30);
        options.setAutomaticReconnect(true);
//        options.setServerURIs(new String[]{mqttProperties.getHost()});
        options.setUserName(mqttProperties.getUsername());
        options.setPassword(mqttProperties.getPassword().toCharArray());
        return options;
    }

    @Bean
    public IMqttAsyncClient iMqttAsyncClientClient(MqttConnectOptions mqttConnectOptions,MqttProperties mqttProperties) throws MqttException, UnknownHostException {
        IMqttAsyncClient  client = new MqttAsyncClient(mqttProperties.getHost(),
                mqttProperties.getClientId() + getLocalHostIP());

        client.setCallback(new DefaultCallback());

        IMqttToken mqttToken = client.connect(mqttConnectOptions);

        mqttToken.waitForCompletion();

        return client;
    }

    /**
     * 回调类
     */
    static class DefaultCallback implements MqttCallback{

        @Override
        public void connectionLost(Throwable cause) {
            logger.warn("mqtt 连接断开");
        }

        @Override
        public void messageArrived(String topic, MqttMessage message) throws Exception {
            logger.debug("messageArrived {} {}",topic,message);
        }

        @Override
        public void deliveryComplete(IMqttDeliveryToken token) {
            logger.debug("deliveryComplete {}",token);
        }
    }

    public static String getLocalHostIP() throws UnknownHostException{
        return InetAddress.getLocalHost().getHostAddress();
    }
}

5.发送订阅工具类

import com.sun.org.slf4j.internal.Logger;
import com.sun.org.slf4j.internal.LoggerFactory;
import org.eclipse.paho.client.mqttv3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;


/**
 * 发送配置
 *
 * @author 123
 */
@Lazy(false)
@Component
public class Mqtt {
    private static final Logger logger = LoggerFactory.getLogger(Mqtt.class);

    private static IMqttAsyncClient iMqttAsyncClient;

    @Autowired
    public void setIMqttAsyncClient(IMqttAsyncClient iMqttAsyncClient) {
        Mqtt.iMqttAsyncClient = iMqttAsyncClient;
    }

    /**
     * 发布消息
     *
     * @param topic
     * @param message
     * @throws MqttException
     */
    public static void publish(String topic, MqttMessage message) throws MqttException {
        iMqttAsyncClient.publish(topic, message);
    }

    public static void publish(String topic, byte[] payload, int qos, boolean retained) throws MqttException {
        iMqttAsyncClient.publish(topic, payload, qos, retained);
    }

    /**
     * 订阅消息
     *
     * @param topic
     * @param qos
     * @throws MqttException
     */
    public static void subscribe(String topic, int qos) throws MqttException {
        iMqttAsyncClient.subscribe(topic, qos);
    }

    public static void subscribe(String topic, int qos, IMqttMessageListener messageListener) throws MqttException {
        iMqttAsyncClient.subscribe(topic, qos, null, null, messageListener);
    }

    public static void subscribe(String[] topic, int[] qos, IMqttMessageListener[] messageListener) throws MqttException {
        iMqttAsyncClient.subscribe(topic, qos, null, null, messageListener);
    }
}

 

6.使用测试

引入本工程,在application.properties 中添加配置,例如

#mqtt配置
mqtt.host=tcp://192.168.1.5:1883
mqtt.username=mqtt
mqtt.password=123456
mqtt.topics=hj/reg,hj/msg,hj/idle

然后调用 Mqtt 工具类发送订阅消息

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页