I'm new to Spring, and I'm trying to insert data into my MySQL from the information received by MQTT.
I created my application with the following code.
public static void main(String[] args) throws InterruptedException {
ConfigurableApplicationContext context = SpringApplication.run(MqttServiceApplication.class, args);
context.registerShutdownHook();
ProductionSubscribe();
}
With the method
public static void ProductionSubscribe() {
try {
IMqttClient client = new MqttClient("tcp://192.168.0.201:1883", new Date().getTime() + "");
client.connect();
ProductionCallBack productionCallBack = new ProductionCallBack();
client.setCallback(productionCallBack);
client.subscribe("/InputCounter/#");
} catch (MqttException e) {
e.printStackTrace();
}
}
So, I implemented MqttCallback
@Component
public class ProductionCallBack implements MqttCallback {
@Autowired
private MachineService machineService;
@Override
public void connectionLost(Throwable throwable) {
System.out.println(throwable);
}
@Override
public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
String name = s.replace("/InputCounter/", "").split("/")[0];
Date now = new Date();
EasyIOModel easyIOModel = new ObjectMapper().readValue(mqttMessage.toString(), EasyIOModel.class);
// Get Machine
Machine machine = machineService.getMachineByNameAndInputNumber(easyIOName);
if (machine == null) {
System.out.println("Error.");
}
}
@Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
System.out.println("deliveryComplete");
}
}
Everything is going well until call the method messageArrived. My service machineService is null, and dont can call services
If I use REST controllers, my services works well... But I don't know which annotations to use in this case with MQTT, so I can call my services.
Thanks,
Just implement CommandLineRunner in principal class. Result:
public class MqttServiceApplication extends SpringBootServletInitializer implements AsyncConfigurer, CommandLineRunner {
@Autowired
ProductionCallBack productionCallBack;
@Override
public void run(String... args) throws Exception {
ProductionSubscribe();
}
}