Skip to content
This repository was archived by the owner on Apr 6, 2019. It is now read-only.

Redis Subscriber

Simon Ninon edited this page Oct 6, 2016 · 12 revisions

Redis Subscriber

The cpp_redis::redis_subscriber is meant to be used for PUB/SUB communication with the Redis server.

Please do not use cpp_redis::redis_client to subscribe to some Redis channels as:

  • the behavior is undefined
  • cpp_redis::redis_client is not meant for that

Methods

void connect(const std::string& host = "127.0.0.1", unsigned int port = 6379, const disconnection_handler& handler = nullptr)

Connects to the Redis Server. Connection is done synchronously. Throws redis_error in case of failure or if client if already connected.

Also sets the disconnection handler which is called whenever a disconnection has occurred. Disconnection handler is an std::function<void(redis_subscriber&)>.

void disconnect(void)

Disconnects client from remote host. Throws redis_error if the client is not connected to any server.

bool is_connected(void)

Returns whether the client is connected or not.

redis_subscriber& subscribe(const std::string& channel, const subscribe_callback& callback)

Subscribes to the given channel and calls subscribe_callback each time a message is published in this channel. subscribe_callback is an std::function<void(const std::string&, const std::string&)>.

The command is not effectively sent immediately, but stored inside an internal buffer until commit() is called.

redis_subscriber& psubscribe(const std::string& pattern, const subscribe_callback& callback)

PSubscribes to the given pattern and calls subscribe_callback each time a message is published in a channel matching the pattern. subscribe_callback is an std::function<void(const std::string&, const std::string&)>.

The command is not effectively sent immediately, but stored inside an internal buffer until commit() is called.

redis_subscriber& unsubscribe(const std::string& channel)

Unsubscribes from the given channel.

The command is not effectively sent immediately, but stored inside an internal buffer until commit() is called.

redis_subscriber& punsubscribe(const std::string& pattern)

Unsubscribes from the given pattern.

The command is not effectively sent immediately, but stored inside an internal buffer until commit() is called.

redis_subscriber& commit(void)

Sends all the commands that have been stored by calling send() since the last commit() call to the Redis server.

That is, pipelining is supported in a very simple and efficient way: sub.subscribe(...).psubscribe(...).unsubscribe(...).commit() will send the 3 commands at once (instead of sending 3 network requests, one for each command, as it would have been done without pipelining).

Clone this wiki locally