O'Reilly logo

ZeroMQ by Pieter Hintjens

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

A Load-Balancing Message Broker

The previous example is half-complete. It can manage a set of workers with dummy requests and replies, but it has no way to talk to clients.

If we add a second frontend ROUTER socket that accepts client requests, and turn our example into a proxy that can switch messages from frontend to backend, we get a useful and reusable tiny load-balancing message broker (Figure 3-7).

Load-balancing broker

Figure 3-7. Load-balancing broker

This broker does the following:

  • Accepts connections from a set of clients

  • Accepts connections from a set of workers

  • Accepts requests from clients and holds these in a single queue

  • Sends these requests to workers using the load-balancing pattern

  • Receives replies back from workers

  • Sends these replies back to the original requesting client

The broker code (listed in Example 3-5) is fairly long, but worth understanding.

Example 3-5. Load-balancing broker (lbbroker.c)

//
//  Load-balancing broker
//  Clients and workers are shown here in-process
//
#include "zhelpers.h"
#include <pthread.h>

#define NBR_CLIENTS 10
#define NBR_WORKERS 3

//  Dequeue operation for queue implemented as array of anything
#define DEQUEUE(q) memmove (&(q)[0], &(q)[1], sizeof (q) - sizeof (q [0]))

//  Basic request-reply client using REQ socket.
//  Since s_send and s_recv can't handle 0MQ binary identities we
//  set a printable text identity to allow routing.
//
static void *
client_task (void ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required