Pub-Sub Message Envelopes
In the pub-sub pattern, we can split the key into a separate message frame that we call an envelope. If you want to use pub-sub envelopes, make them yourself. Itâs optional, and in previous pub-sub examples, we didnât do this. Using a pub-sub envelope is a little more work for simple cases, but itâs cleaner, especially for real cases, where the key and the data are naturally separate things.
Figure 2-15 shows is what a publish-subscribe message with an envelope looks like.
Figure 2-15. Pub-sub envelope with separate key
Recall that subscriptions do a prefix match. That is, they look for âall messages starting with XYZ.â The obvious question is: how to delimit keys from data so that the prefix match doesnât accidentally match data. The best answer is to use an envelope, because the match wonât cross a frame boundary.
Here is a minimalist example of how pub-sub envelopes look in code. This publisher (Example 2-15) sends messages of two types, A and B. The envelope holds the message type.
Example 2-15. Pub-sub envelope publisher (psenvpub.c)
//
// Pub-sub envelope publisher
// Note that the zhelpers.h file also provides s_sendmore
//
#include "zhelpers.h"
int
main
(
void
)
{
// Prepare our context and publisher
void
*
context
=
zmq_ctx_new
();
void
*
publisher
=
zmq_socket
(
context
,
ZMQ_PUB
);
zmq_bind
(
publisher
,
"tcp://*:5563"
);
while
(
1
)
{
// Write ...
Get ZeroMQ now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.