RPC style request with MQTT

我只是一个虾纸丫 提交于 2020-08-23 09:46:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!