Representing State as Key-Value Pairs
Weâll develop the Clone pattern in stages, solving one problem at a time. First, letâs look at how to update a shared state across a set of clients. We need to decide how to represent our state, as well as the updates. The simplest plausible format is a key-value store, where one key-value pair represents an atomic unit of change in the shared state.
We looked at a simple pub-sub example in Chapter 2, the weather server and client. Letâs change the server to send key-value pairs, and the client to store these in a hash table. This lets us send updates from one server to a set of clients using the classic pub-sub model (Figure 5-3).
Figure 5-3. Publishing state updates
An update is either a new key-value pair, a modified value for an existing key, or a deleted key. We can assume for now that the whole store fits in memory and that applications access it by key, such as by a hash table or dictionary. For larger stores and some kind of persistence weâd probably store the state in a database, but thatâs not relevant here.
Our first attempt at the server is shown in Example 5-13.
Example 5-13. Clone server, Model One (clonesrv1.c)
//
// Clone server-Model One
//
// Lets us build this source without creating a library
#include "kvsimple.c"
int
main
(
void
)
{
// Prepare our context and publisher socket
zctx_t
*
ctx
=
zctx_new
();
void
*
publisher ...
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.