setCleanSession(false) not working with MqttClient/MqttCallbackExtended [message #1866450] |
Thu, 30 May 2024 01:14  |
Eclipse User |
|
|
|
I have a setup with mqtt/mosquitto with persistence enabled and verified (using mosquitto_sub -c). Even with QoS=1 and setCleanSession(false) I am loosing messages that is received when my subscription service is stopped.
My expectation is that when I stop and restart after few secs/mins the messages that is received during this time in the server will be available when the subscriber comes back.
This happens when I am using CLI (mosquitto_sub -c..).
Here is the broad codebase. Appreciate any pointers.
public class MqttSubsc implements MqttCallbackExtended{
public MqttSubsc(String mqttUrl, String deviceToken, ..)
{
..
mqttConnectOptions = new MqttConnectOptions();
mqttConnectOptions.setCleanSession(false);
mqttConnectOptions.setUserName(deviceToken);
if (password != null && password.length() > 0)
{
mqttConnectOptions.setPassword(password.toCharArray());
}
mqttConnectOptions.setAutomaticReconnect(true);
}
public void subscribe() throws MqttException{
this.connect();
}
private void connect() throws MqttException
{
..
this.client = new MqttClient(mqttUrl, this.clientid);
this.client.setCallback(this);
try
{
this.client.connect(this.mqttConnectOptions);
}
catch (MqttException mqttex)
{
mqttex.printStackTrace();
}
}
public void connectionLost(Throwable cause){...}
@Override
public void connectComplete(boolean arg0, String arg1){
try{
this.client.subscribe(this.topic,this.qos);
}catch (MqttException mqttex)
{
mqttex.printStackTrace();
}
}
public void deliveryComplete(IMqttDeliveryToken token){..}
public void messageArrived(String topic, MqttMessage message) throws MqttException
{
//Handling message here
}
}
[Updated on: Thu, 30 May 2024 01:43] by Moderator
|
|
|
Re: setCleanSession(false) not working with MqttClient/MqttCallbackExtended [message #1866513 is a reply to message #1866450] |
Fri, 31 May 2024 05:54  |
Eclipse User |
|
|
|
Found the problem. I was unsubscribing when the process is shutdown which I should not. If unsubscribed then I would miss all the offline messages even when we subscribe to the topic.
So when setCleanSession is false, DO NOT unsubscribe while disconnecting/closing.
// Add a shutdown hook to unsubscribe and disconnect
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
try {
LOGGER.info("Please wait..closing subscriber gracefully.");
if (this.client.isConnected()) {
try {
//IMP: If the setCleanSession is false, upon closure of connect, DO NOT unsubscribe
//Upon Unsubscribing, we will loose the messages publish during offline.
//this.client.unsubscribe(this.topic);
this.client.disconnect();
}finally {
this.client.close();
LOGGER.info("Subscriber connection closed successfully.");
}
}
} catch (MqttException e) {
e.printStackTrace();
LOGGER.error(e);
}
|
|
|
Powered by
FUDForum. Page generated in 0.17760 seconds