首页 > 解决方案 > How to implement a request-response pattern with paho mqtt java?

问题描述

I'd like to use Paho MQTT Java and implement some "request-response" pattern. What I mean by that is that in some instances the client has to talk to the server and expects a specific answer to a specific request. It feels like this lib has everything needed to match a request and a response, but I can't quite put it together.

I found I can retrieve a token via deliveryComplete, and that I can do a setActionCallback on this token. But first, I'm not entirely sure what an "action" means. Then, if it means what I think it means, how to get the actual response to my request from there?

sampleClient.setCallback(new MqttCallback() {
    @Override
    public void connectionLost(Throwable cause) {
    }

    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {
        System.out.println(topic);
        System.out.println("setCallback: "+ message.toString());
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {
        System.out.println(token.getMessageId());
        token.setActionCallback(new IMqttActionListener() {
            @Override
            public void onSuccess(IMqttToken asyncActionToken) {
                var response = asyncActionToken.getResponse();

                try {
                    System.out.println(new String(response.getPayload()));
                } catch (MqttException e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
            }
        });
    }
});

标签: javamqttpaho

解决方案


MQTT 对于任何类型的 1 Request - 1 Response 来说都是多余的……这就是 API 的用途。MQTT 最适合一个节点向一个或多个接入主题的节点发送数据。发送节点(发布者)不需要知道任何接收节点(订阅者)......他们只需要就使用的主题达成一致。

话虽如此,您可以实现“查询”发布,并查找您将订阅的“回复”MQTT 消息。过去我已经这样做了,多个节点可以从知道回复是什么中受益。所以它可能看起来像这样:发布 -q/system/status并订阅r/system/statusr/system/#


推荐阅读