Skip to content
Dan Parnham edited this page May 31, 2016 · 2 revisions

The Redis classes act as a wrapper around the hiredis C library. They deal with connections and handling the lifetime of redisReply structures.

Redis.hpp

This contains the base Redis class which deals with synchronous connections and provides a simple Command function that allows you invoke any Redis command. It takes the same arguments as the hiredis redisCommand as in the example below. The class also contains many helper functions for invoking standard Redis commands.

#include <emergent/redis/Redis.hpp>
using namespace emergent::redis;

int main(int argc, char *argv[])
{
    Redis redis;

    if (redis.Initialise(false, "127.0.0.1", 6379))
    {
        // Invoke any Redis command
        auto reply = redis.Command("GET %s", "mykey");

        // The Reply class contains helper functions for retrieving string, numeric and 
        // array values from a Redis response.
        cout << "Value at 'mykey' was " << reply.AsString() << endl;

        // There are helper functions to achieve the same
        string value = redis.Get("mykey");
    }
}

RedisMultiplexer.hpp

This is a thread-safe implementation which maintains a single Redis connection. It supports automatic pipelining of concurrent calls. Since RedisMultiplexer is derived from Redis it is identical in use and contains all of the same helper functions.

RedisBinBag.hpp

Since Redis is binary safe, RedisBinBag is derived from the Redis class and adds functions specifically for handling binary data. It can be used to store/retrieve images of type Image<> and other binary data stored as either Buffer<> or std::vector<>.

Subscription.hpp

The standard Redis class supports the PUBLISH command but subscriptions require a different approach. The Subscription class wraps some of the asynchronous hiredis functionality to provide a C++11 friendly interface. It takes a std::function for the message callback so lambdas can be used. It also owns the event loop required by hiredis but is not itself threaded, therefore the event loop needs to be driven from the thread that owns a Subscription instance via the Listen function.

#include <emergent/redis/Subscription.hpp>
using namespace emergent::redis;

int main(int argc, char *argv[])
{
    Subscription sub;

    // Initialise with a callback function, no channels and default
    // connection parameters.
    sub.Initialise([](string channel, string message) {
        cout << channel << ": " << message << endl;
    });

    // Add a channel subscription
    sub.Add("mychannel");

    while (true)
    {
        // Drive the event loop
        sub.Listen();
        this_thread::sleep_for(milliseconds(10));
    }
}
Clone this wiki locally