java基于mqttv3接收mqtt消息,配置mqtt
mqtt连接、配置、以及接收消息的代码
@Component
public class ClientMQTT implements CommandLineRunner {
@Value("${activemq.url}")
private String host;
@Value("${activemq.topic}")
public String topic;
@Value("${activemq.clientId}")
private String clientId;
@Value("${activemq.username}")
private String userName;
@Value("${activemq.password}")
private String passWord;
public MqttClient client;
private MqttConnectOptions options;
protected Log log = LogFactory.getLog(this.getClass());
@Override
public void run(String... args) {
try {
// host为主机名,clientid即连接MQTT的客户端ID,一般以唯一标识符表示,MemoryPersistence设置clientid的保存形式,默认为以内存保存
client = new MqttClient(host, clientId, new MemoryPersistence());
// MQTT的连接设置
options = new MqttConnectOptions();
// 设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录,这里设置为true表示每次连接到服务器都以新的身份连接
options.setCleanSession(true);
// 设置连接的用户名
options.setUserName(userName);
// 设置连接的密码
options.setPassword(passWord.toCharArray());
// 设置超时时间 单位为秒
options.setConnectionTimeout(10);
// 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线,但这个方法并没有重连的机制
options.setKeepAliveInterval(20);
//设置自动连接
options.setAutomaticReconnect(true);
// 设置回调
client.setCallback(new MqttCallbackExtended() {
//连接成功回调,需要重新订阅主题
@Override
public void connectComplete(boolean reconnect, String serverURI) {
sendNotify(true);
subscribe();
}
@Override
public void connectionLost(Throwable cause) {
retryConnection(3);
}
@Override
public void deliveryComplete(IMqttDeliveryToken token) {
token.isComplete();
}
@Override
public void messageArrived(String topic, MqttMessage message) {
}
});
MqttTopic mqttTopic = client.getTopic(topic);
//setWill方法,如果项目中需要知道客户端是否掉线可以调用该方法。设置最终端口的通知消息
options.setWill(mqttTopic, "close".getBytes(), 2, true);
client.connect(options);
subscribe();
} catch (Exception e) {
log.error("mqtt异常" + e.getMessage());
e.printStackTrace();
}
}
private void subscribe() {
try {
//订阅队列
client.subscribe(topic, 2, (topic, message) -> {
String msg = new String(message.getPayload(), StandardCharsets.UTF_8);
log.warn("mqtt收到信息:"+msg);
//处理消息
});
} catch (MqttException e) {
log.error("mqtt异常" + e.getMessage());
}
}
private void retryConnection(int retryNumber) {
//当重试多次,依旧失败,就是机器故障,需要通知人工处理
if (retryNumber < 0) {
sendNotify(false);
}
try {
client.reconnect();
TimeUnit.SECONDS.sleep(30);
if (!client.isConnected()) {
retryConnection(--retryNumber);
}
} catch (MqttException | InterruptedException e) {
log.error("mqtt异常:"+e.getMessage());
}
}
//发送重试通知
private void sendNotify(boolean isSuccess) {
if (isSuccess){
log.debug("mqtt连接成功");
}else log.error("mqtt连接失败");
}
}
类上加@Component
注解是为了让项目启动时加载就运行加载自动连接mqtt。
参考了以下博客,感谢两位大佬的帖子
https://blog.csdn.net/qq_36669747/article/details/105613275
https://blog.csdn.net/qq_41338249/article/details/103448917