SpringBoot简单集成MQTT
记录:这两天在写MQ的东西,就顺便记录下
注意的是mqtt不能储存数据,就算储存也是只能储存最后一条,所以当服务端断了不能及时接收数据时容易造成数据丢失,但mqtt的优点就是省流量
1.导入依赖
<dependency>
<groupId>org.eclipse.pahogroupId>
<artifactId>org.eclipse.paho.client.mqttv3artifactId>
<version>1.2.0version>
dependency>
<dependency>
<groupId>org.fusesource.mqtt-clientgroupId>
<artifactId>mqtt-clientartifactId>
<version>1.14version>
dependency>
2.添加配置文件 application.yml
spring.mqtt.username: (账号)
spring.mqtt.password: (密码)
spring.mqtt.url: tcp://IP:1883(端口默认1883)
spring.mqtt.client.id: 1
spring.mqtt.topic: /ksp/test
spring.mqtt.completionTimeout: 3000
3.编写配置类
@Component
public class MqttCofigBean {
@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.topic}")
private String msgTopic;
@Value("${spring.mqtt.completionTimeout}")
private int completionTimeout;
public String getUsername() {
return this.username;
}
public String getPassword() {
return this.password;
}
public String getHostUrl() {
return this.hostUrl;
}
public String getClientId() {
return this.clientId;
}
public String[] getMsgTopic() {
String[] topic=msgTopic.split(",");
return topic;
}
public int getCompletionTimeout() {
return this.completionTimeout;
}
}
4.编写客户端
@Component
public class MqttConsumer implements ApplicationRunner {
private static Logger logger= LoggerFactory.getLogger(MqttConsumer.class);
private static MqttClient client;
private static MqttTopic mqttTopic;
@Autowired
public MqttCofigBean mqttCofigBean;
@Override
public void run(ApplicationArguments args) throws Exception {
logger.info("初始化启动MQTT连接");
this.connect();
}
private void connect() throws Exception{
client = new MqttClient(mqttCofigBean.getHostUrl(),mqttCofigBean.getClientId(), new MemoryPersistence());
MqttConnectOptions options = new MqttConnectOptions();
options.setCleanSession(false);
options.setUserName(mqttCofigBean.getUsername());
options.setPassword(mqttCofigBean.getPassword().toCharArray());
options.setCleanSession(false);
options.setConnectionTimeout(30);
options.setKeepAliveInterval(20);
try {
String[] msgtopic = mqttCofigBean.getMsgTopic();
int[] qos = new int[msgtopic.length];
for (int i = 0; i < msgtopic.length; i++) {
qos[i]=0;
}
client.setCallback(new TopMsgCallback(client,options,msgtopic,qos));
client.connect(options);
client.subscribe(msgtopic,qos);
logger.info("MQTT连接成功:"+mqttCofigBean.getClientId()+":"+client);
} catch (Exception e) {
logger.error("MQTT连接异常:"+e);
}
}
public void reConnect() throws Exception {
if(null != client) {
this.connect();
}
}
public void subscribe(String topic,int qos){
try {
logger.info("topic:"+topic);
client.subscribe(topic, qos);
MqttMessage mqttMessage = new MqttMessage();
mqttMessage.setPayload(new String("消息11111111").getBytes());
client.publish(topic,mqttMessage);
} catch (MqttException e) {
e.printStackTrace();
}
}
public MqttClient getClient() {
return client;
}
public void setClient(MqttClient client) {
this.client = client;
}
public MqttTopic getMqttTopic() {
return mqttTopic;
}
public void setMqttTopic(MqttTopic mqttTopic) {
this.mqttTopic = mqttTopic;
}
}
5.编写服务端
@Component
public class TopMsgCallback implements MqttCallback {
private static Logger logger= LoggerFactory.getLogger(TopMsgCallback.class);
private MqttClient client;
private MqttConnectOptions options;
private String[] topic;
private int[] qos;
public TopMsgCallback() {}
public TopMsgCallback(MqttClient client, MqttConnectOptions options,String[] topic,int[] qos) {
this.client = client;
this.options = options;
this.topic=topic;
this.qos=qos;
}
public void connectionLost(Throwable cause) {
logger.info("MQTT连接断开,发起重连");
while(true) {
try {
Thread.sleep(30000);
client.connect(options);
client.subscribe(topic,qos);
logger.info("MQTT重新连接成功:"+client);
break;
} catch (Exception e) {
e.printStackTrace();
continue;
}
}
}
public void deliveryComplete(IMqttDeliveryToken token) {
}
public void messageArrived(String topic, MqttMessage message) throws Exception {
String msg = new String(message.getPayload());
logger.info("topic:"+topic);
logger.info("msg:"+msg);
}
public byte[] getBytesFromObject(Serializable obj) throws Exception {
if (obj == null) {
return null;
}
ByteArrayOutputStream bo = new ByteArrayOutputStream();
ObjectOutputStream oo = new ObjectOutputStream(bo);
oo.writeObject(obj);
return bo.toByteArray();
}
}