我使用rxmqtt(使用rxjava和paho)与mqtt代理进行通信。我使用javax接受休息请求并将一些内容发布到代理并等待响应。如果我一次发出一个请求,下面的代码工作正常,但如果我有多个并发请求,它只返回最后一个请求的响应,其他请求属于超时异常。
mqttConn.getMqttMessages()返回一个已经订阅了我需要的所有主题的flowable:
public Flowable<MqttMessage> getMqttMessages() {
return this.obsClient.subscribe("pahoRx/fa/#", 1);
}
和MqttConnection是一个单例,因为我只需要一个连接到代理,所有发布都在这个连接中完成 我注意到我的queryParam id在Web服务请求的每个线程执行中都是不同的(预期的行为),但是当它进入代码的订阅部分时,它只考虑最后一个id值并且没有通过我的验证takeUntil方法:
mqttConn.getMqttMessages().timeout(20, TimeUnit.SECONDS).takeUntil(msgRcv -> {
System.out.println("received: " + new String(msgRcv.getPayload()) + " ID: " + id);
return id.equals(new String(msgRcv.getPayload()));
}).blockingSubscribe(msgRcv -> {
final byte[] body = msgRcv.getPayload();
System.out.println(new String(body)); //printing... but not sending the reponse
response.set("Message Receiced: " + new String(msgRcv.getPayload()));
return;
}, e -> {
if (e instanceof TimeoutException) {
response.set("Timeout Occured");
} else {
response.set("Some kind of error occured " + e.getLocalizedMessage());
}
});
问题是,为什么只考虑每个请求应该拥有自己的独立线程时收到的最后一个id?我已经尝试将mqttConn.getMqttConnection()作为ThreadLocal对象...没有修复。
完整的WS代码:
@Path("/test")
@GET
public String test(@QueryParam("id") String id) throws InterruptedException, MqttException {
String funcExec = "pahoRx/fe/";
String content = "unlock with single connection to broker";
int qos = 1;
AtomicReference<String> response = new AtomicReference<String>();
response.set("Initial Value");
MqttConnection mqttConn = MqttConnection.getMqttConnection();
ObservableMqttClient obsClient = mqttConn.getBrokerClient();
MqttMessage msg = MqttMessage.create(78, content.getBytes(), qos, false);
String topicPub = funcExec + id;
obsClient.publish(topicPub, msg).subscribe(t -> {
System.out.println("Message Published");
}, e -> {
System.out.println("Failed to publish message: " + e.getLocalizedMessage());
});
mqttConn.getMqttMessages().timeout(20, TimeUnit.SECONDS).takeUntil(msgRcv -> {
System.out.println("received: " + new String(msgRcv.getPayload()) + " ID: " + id);
return id.equals(new String(msgRcv.getPayload()));
}).blockingSubscribe(msgRcv -> {
final byte[] body = msgRcv.getPayload();
System.out.println(new String(body)); //printing... but not sending the reponse
response.set("Message Receiced: " + new String(msgRcv.getPayload()));
return;
}, e -> {
if (e instanceof TimeoutException) {
response.set("Timeout Occured");
} else {
response.set("Some kind of error occured " + e.getLocalizedMessage());
}
});
return response.get();
}
我希望解释清楚!
事先提前