我是Spring的新手,我正尝试从MQTT收到的信息中将数据插入MySQL。
我使用以下代码创建了我的应用程序。
public static void main(String[] args) throws InterruptedException {
ConfigurableApplicationContext context = SpringApplication.run(MqttServiceApplication.class, args);
context.registerShutdownHook();
ProductionSubscribe();
}
使用方法
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();
}
}
所以,我实现了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");
}
}
一切正常,直到调用messageArrived方法。我的服务machineService为null,无法调用服务
如果使用REST控制器,则我的服务运行良好...但是我不知道在这种情况下,MQTT使用哪种注释,因此可以调用我的服务。
谢谢,
只需在主体类中实现CommandLineRunner。结果:
public class MqttServiceApplication extends SpringBootServletInitializer implements AsyncConfigurer, CommandLineRunner {
@Autowired
ProductionCallBack productionCallBack;
@Override
public void run(String... args) throws Exception {
ProductionSubscribe();
}
}