- springboot 集成mqtt实现发布、订阅消息的功能
- 首先在pom.xml文件中加入依赖
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-mqtt</artifactId>
</dependency>
- application.yml配置
mqtt:
host: tcp://xx.xx.xx.xx:1883
topics: scrm_user/#
clientId: clientId
maxInflight: 20
username: admin
password: public
- MqttFactory
import com.alibaba.fastjson.JSONObject;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MqttFactory {
@Value("${mqtt.host}")
private String host;
@Value("${mqtt.username}")
private String username;
@Value("${mqtt.password}")
private String password;
private final static Logger logger = LoggerFactory.getLogger(MqttFactory.class);
private static MqttFactory factory;
private static MqttClient CLIENT;
public MqttFactory() {
factory = this;
}
public static void sendMessage(String clientId, String topic, Object message) {
sendMessage(clientId, topic, JSONObject.toJSONString(message));
}
public static void sendMessage(String clientId, String topic, String message) {
MqttMessage mqttMessage = new MqttMessage();
mqttMessage.setQos(1);
mqttMessage.setRetained(true);
mqttMessage.setPayload(message.getBytes());
try {
getClient(clientId).publish(topic, mqttMessage);
logger.info("主题【" + topic + "】发送消息成功:" + message);
if(logger.isDebugEnabled()) {
logger.debug("主题【" + topic + "】发送消息成功:" + message);
}
} catch (Exception e) {
logger.error("主题【" + topic + "】发送消息失败:" + e.getMessage() + "\n消息内容:" + message, e);
}
}
public static void subscribe(String clientId, String topic) throws MqttException {
getClient(clientId).subscribe(topic, 1);
logger.info("主题【" + topic + "】订阅成功");
}
private static MqttClient getClient(String clientId) {
if(CLIENT != null) {
return CLIENT;
}
synchronized(MqttFactory.class) {
if(CLIENT != null) {
return CLIENT;
}
try {
CLIENT = createClient(clientId);
} catch (MqttException e) {
throw new RuntimeException(e.getMessage(), e);
}
return CLIENT;
}
}
private static MqttClient createClient(String clientId) throws MqttException {
MqttClient CLIENT = new MqttClient(factory.host, clientId, new MemoryPersistence());
MqttConnectOptions options = new MqttConnectOptions();
options.setCleanSession(true);
options.setUserName(factory.username);
options.setPassword(factory.password.toCharArray());
options.setConnectionTimeout(10);
options.setKeepAliveInterval(60);
options.setAutomaticReconnect(true);
CLIENT.connect(options);
return CLIENT;
}
}