In addition to the publish-subscribe messaging modes supported by the standard MQTT protocol, ApsaraMQ for MQTT it also supports the Point-to-Point (Point to Point) mode. This topic describes the concepts, principles, and usage of the P2P model. ApsaraMQ for MQTT Point-to-point message sending and receiving.
What is the P2P model?
P2P, as its name implies, is a one-to-one messaging model where only one message sender and one message receiver are involved. The publish-subscribe model is usually used in one-to-many or many-to-many message transmission scenarios where one or more message senders and many message receivers are involved.
In the P2P model, the sender knows the information about the expected receiver when sending a message, and expects that the message will be consumed only by a specific client. The sender directly specifies the receiver in a topic when sending a message. The receiver can obtain the message without subscribing to the topic in advance.
The P2P model not only saves the subscription registration cost for the receiver but, due to the independently optimized messaging link, also reduces the push latency.
Differences between the P2P model and the publish-subscribe model
In ApsaraMQ for MQTT the differences between the P2P model and the publish-subscribe model for sending and receiving messages are as follows:
- In the publish-subscribe model, the message sender needs to send the messages of the topic to which the receiver has subscribed. In the P2P model, the receiver does not need to subscribe to the topic, and the sender can send messages directly to the target client according to the standards.
- In the publish-subscribe model, the receiver needs to subscribe to the topic in advance to receive messages from the sender. In the P2P model, the receiver does not need to subscribe to the topic in advance. Therefore, the program logic at the receiver is simplified and the subscription cost is saved.
Send P2P messages
When using the MQTT SDK to send P2P messages, you must set the level-2 topic to "p2p" and the level-3 topic to the client ID of the target receiver.
String p2pTopic =topic+"/p2p/GID_xxxx@@@DEVICEID_001";
Use ApsaraMQ for RocketMQ when using the [******] SDK to send P2P messages, you only need to set the subtopic attribute to the preceding subtopic string because the parent Topic and subtopic are set separately.
The links to multi-language sample codes for sending P2P messages are shown in the following table.
|. NET sample code
|C sample code
|Java sample code
|Python sample code
|PHP Sample code
Receive P2P messages
The client does not need to subscribe to P2P messages. Instead, it can receive P2P messages after initialization.