问题
what is the best way to implement RPC style communication (synchronous request/response) with MQTT? Or would it even make sense to put another interface (e.g. REST api) into use?
Thanks in advance!
回答1:
MQTT is a PUB/SUB system and doesn't lend itself well to RPC. While you could possibly shoehorn something on top of MQTT to simulate the synchronicity required, you are probably better off looking for a system which provides real RPC semantics.
That said, depending on your application, you can subscribe to multiple MQTT topics and simulate round-trip communication by PUBlishing on one topic and listening for a response on a second topic. Note though, that this is by nature not synchronous.
For example, you could PUBlish a "question" to topic/query
and expect a response on topic/response
.
回答2:
What I've done in my applications is include a response topic in my messages. The sender would generate a topic using a uuid then subscribe to that topic. Then would send a message containing the response topic, the receiver(s) would send a reply to this topic. Once the send receives the reply it would unsubscribe to the topic. Both sender and receiver are asynchronous and yet can perform a transaction.
Pseudo code:
sender generate uuid subscribe( topic=uuid ) msg = { ... resp_topic: uuid } publish( topic, msg ) receiver on_message topic is from sender do some work publish( sender_data['resp_topic'], result ) sender on_message topic is resp_topic get result unsubscribe( resp_topic )
来源:https://stackoverflow.com/questions/20483012/rpc-style-request-with-mqtt