在MQTT的messageArrived
方法中无法直接调用Service层进行CRUD操作,因为messageArrived
方法通常是在一个单独的线程中执行的,而Service层的操作可能需要在应用程序的主线程中进行。解决方案如下:
/** * Mqtt连接回调函数 ,用来接收已经订阅的消息 */ public class MqttReceiveCallback implements MqttCallback { private ExecutorService executor; public MqttReceiveCallback() { // 创建一个固定大小的线程池 executor = Executors.newFixedThreadPool(10); } @Override public void connectionLost(Throwable throwable) { System.out.println("Client 连接丢失 : "+ throwable.getMessage()); } @Override public void messageArrived(String topic, MqttMessage message) throws Exception { System.out.println("Client 接收消息主题 : " + topic); System.out.println("Client 接收消息Qos : " + message.getQos()); System.out.println("Client 接收消息内容 : " + new String(message.getPayload())); executor.submit(() -> { try { // 在异步任务中调用Service层进行CRUD操作 DataStaticService datastaticService = (DataStaticService)SpringContextUtil.getBean("datastaticService"); Datastatic datastatic = JSON.parseObject(message.getPayload(), Datastatic.class); //将数据保存至数据库 datastaticService.save(datastatic); } catch (Exception e) { e.printStackTrace(); // 处理异常情况 } }); } @Override public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) { } }
public class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
/**
* 实现ApplicationContextAware接口的回调方法,设置上下文环境
*/
public void setApplicationContext(ApplicationContext applicationContext){
SpringContextUtil.applicationContext = applicationContext;
}
public static ApplicationContext getApplicationContext(){
return applicationContext;
}
/**
* 获取对象
*/
public static Object getBean(String name) throws BeansException{
return applicationContext.getBean(name);
}
}
网上试了很多种方法都没用,还是chatgpt找到了答案!