I have a Spring Boot application that I’m using with Mqtt Paho. I’ve created an Mqtt Configuration class to connect to the broker and subscribe to a test topic. I also have an MqttListener class to handle messages. The Listener bean is being initialized but my Mqtt methods are not being called. I have determined it it most liekly because my MqttClient is not being injected into this class, but I could be wrong.
Here is my MqttClient:
package com.example.javaproject.listener;
@Configuration
public class MqttConfig {
@Bean
public MqttClient mqttClient() throws MqttException {
MqttClient client = new MqttClient(broker, clientId);
MqttConnectOptions options = new MqttConnectOptions();
options.setUserName("skaxi");
options.setPassword("M@ji2222".toCharArray());
client.connect(options);
if (client.isConnected()) {
System.out.println("client connected");
client.subscribe("test-topic");
System.out.println("subscribed to topics");
}
return client;
}
}
Here is my Listener:
package com.example.javaproject.config;
@Service
public class MqttMessageListener implements MqttCallbackExtended{
@Autowired
MessageRepository messageRepository;
@Autowired
private MqttClient mqttClient;
public MqttMessageListener(){
}
@PostConstruct
public void init() {
System.out.println("MqttMessageListener initialized successfully");
}
@Override
public void connectComplete(boolean b, String s) {
System.out.println("connected message from listener");
}
@Override
public void connectionLost(Throwable throwable) {
System.out.println("connection lost");
}
@Override
public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
String content = mqttMessage.toString();
Message message = new Message(topic, content);
System.out.println("message arrived triggered: " + content);
try{
messageRepository.save(message);
System.out.println("message saved to database");
}catch(Exception e){
System.out.println("error saving to database: " + e.getMessage());
}
}
@Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
System.out.println("delivery complete");
}
}
Any ideas would be appreciated. Thank you
I have tried injecting the client through the Listeners constructor as well as field injection but I still get nothing. I have seen in the logs that the mqttClient bean is being created so maybe that’s not the problem.