]> git.saurik.com Git - redis.git/blame - deps/hiredis/README.md
handle end of space on device in a better way
[redis.git] / deps / hiredis / README.md
CommitLineData
24f753a8
PN
1# HIREDIS
2
3Hiredis is a minimalistic C client library for the [Redis](http://redis.io/) database.
4
5It is minimalistic because it just adds minimal support for the protocol, but
6at the same time it uses an high level printf-alike API in order to make it
7much higher level than otherwise suggested by its minimal code base and the
8lack of explicit bindings for every Redis command.
9
10Apart from supporting sending commands and receiving replies, it comes with
11a reply parser that is decoupled from the I/O layer. It
12is a stream parser designed for easy reusability, which can for instance be used
13in higher level language bindings for efficient reply parsing.
14
15Hiredis only supports the binary-safe Redis protocol, so you can use it with any
16Redis version >= 1.2.0.
17
18The library comes with multiple APIs. There is the
19*synchronous API*, the *asynchronous API* and the *reply parsing API*.
20
21## UPGRADING
22
23Version 0.9.0 is a major overhaul of hiredis in every aspect. However, upgrading existing
24code using hiredis should not be a big pain. The key thing to keep in mind when
25upgrading is that hiredis >= 0.9.0 uses a `redisContext*` to keep state, in contrast to
26the stateless 0.0.1 that only has a file descriptor to work with.
27
28## Synchronous API
29
30To consume the synchronous API, there are only a few function calls that need to be introduced:
31
32 redisContext *redisConnect(const char *ip, int port);
33 void *redisCommand(redisContext *c, const char *format, ...);
34 void freeReplyObject(void *reply);
35
36### Connecting
37
38The function `redisConnect` is used to create a so-called `redisContext`. The context is where
39Hiredis holds state for a connection. The `redisContext` struct has an `error` field that is
40non-NULL when the connection is in an error state. It contains a string with a textual
41representation of the error. After trying to connect to Redis using `redisConnect` you should
42check the `error` field to see if establishing the connection was successful:
43
44 redisContext *c = redisConnect("127.0.0.1", 6379);
45 if (c->error != NULL) {
46 printf("Error: %s\n", c->error);
47 // handle error
48 }
49
50### Sending commands
51
52There are several ways to issue commands to Redis. The first that will be introduced is
53`redisCommand`. This function takes a format similar to printf. In the simplest form,
54it is used like this:
55
56 reply = redisCommand(context, "SET foo bar");
57
58The specifier `%s` interpolates a string in the command, and uses `strlen` to
59determine the length of the string:
60
61 reply = redisCommand(context, "SET foo %s", value);
62
63When you need to pass binary safe strings in a command, the `%b` specifier can be
64used. Together with a pointer to the string, it requires a `size_t` length argument
65of the string:
66
67 reply = redisCommand(context, "SET foo %b", value, valuelen);
68
69Internally, Hiredis splits the command in different arguments and will
70convert it to the protocol used to communicate with Redis.
71One or more spaces separates arguments, so you can use the specifiers
72anywhere in an argument:
73
74 reply = redisCommand("SET key:%s %s", myid, value);
75
76### Using replies
77
78The return value of `redisCommand` holds a reply when the command was
79successfully executed. When the return value is `NULL`, the `error` field
80in the context can be used to find out what was the cause of failure.
81Once an error is returned the context cannot be reused and you should set up
82a new connection.
83
84The standard replies that `redisCommand` are of the type `redisReply`. The
85`type` field in the `redisReply` should be used to test what kind of reply
86was received:
87
88* **`REDIS_REPLY_STATUS`**:
89 * The command replied with a status reply. The status string can be accessed using `reply->str`.
90 The length of this string can be accessed using `reply->len`.
91
92* **`REDIS_REPLY_ERROR`**:
93 * The command replied with an error. The error string can be accessed identical to `REDIS_REPLY_STATUS`.
94
95* **`REDIS_REPLY_INTEGER`**:
96 * The command replied with an integer. The integer value can be accessed using the
97 `reply->integer` field of type `long long`.
98
99* **`REDIS_REPLY_NIL`**:
100 * The command replied with a **nil** object. There is no data to access.
101
102* **`REDIS_REPLY_STRING`**:
103 * A bulk (string) reply. The value of the reply can be accessed using `reply->str`.
104 The length of this string can be accessed using `reply->len`.
105
106* **`REDIS_REPLY_ARRAY`**:
107 * A multi bulk reply. The number of elements in the multi bulk reply is stored in
108 `reply->elements`. Every element in the multi bulk reply is a `redisReply` object as well
109 and can be accessed via `reply->elements[..index..]`.
110 Redis may reply with nested arrays but this is fully supported.
111
112Replies should be freed using the `freeReplyObject()` function.
113Note that this function will take care of freeing sub-replies objects
114contained in arrays and nested arrays, so there is no need for the user to
115free the sub replies (it is actually harmful and will corrupt the memory).
116
117### Cleaning up
118
119To disconnect and free the context the following function can be used:
120
121 void redisFree(redisContext *c);
122
123This function immediately closes the socket and then free's the allocations done in
124creating the context.
125
126### Sending commands (cont'd)
127
128Together with `redisCommand`, the function `redisCommandArgv` can be used to issue commands.
129It has the following prototype:
130
131 void *redisCommandArgv(redisContext *c, int argc, const char **argv, const size_t *argvlen);
132
133It takes the number of arguments `argc`, an array of strings `argv` and the lengths of the
134arguments `argvlen`. For convenience, `argvlen` may be set to `NULL` and the function will
135use `strlen(3)` on every argument to determine its length. Obviously, when any of the arguments
136need to be binary safe, the entire array of lengths `argvlen` should be provided.
137
138The return value has the same semantic as `redisCommand`.
139
140### Pipelining
141
142To explain how Hiredis supports pipelining in a blocking connection, there needs to be
143understanding of the internal execution flow.
144
145When any of the functions in the `redisCommand` family is called, Hiredis first formats the
146command according to the Redis protocol. The formatted command is then put in the output buffer
147of the context. This output buffer is dynamic, so it can hold any number of commands.
148After the command is put in the output buffer, `redisGetReply` is called. This function has the
149following two execution paths:
150
1511. The input buffer is non-empty:
152 * Try to parse a single reply from the input buffer and return it
153 * If no reply could be parsed, continue at *2*
1542. The input buffer is empty:
155 * Write the **entire** output buffer to the socket
156 * Read from the socket until a single reply could be parsed
157
158The function `redisGetReply` is exported as part of the Hiredis API and can be used when a reply
159is expected on the socket. To pipeline commands, the only things that needs to be done is
160filling up the output buffer. For this cause, two commands can be used that are identical
161to the `redisCommand` family, apart from not returning a reply:
162
163 void redisAppendCommand(redisContext *c, const char *format, ...);
164 void redisAppendCommandArgv(redisContext *c, int argc, const char **argv, const size_t *argvlen);
165
166After calling either function one or more times, `redisGetReply` can be used to receive the
167subsequent replies. The return value for this function is either `REDIS_OK` or `REDIS_ERR`, where
168the latter means an error occurred while reading a reply. Just as with the other commands,
169the `error` field in the context can be used to find out what the cause of this error is.
170
171The following examples shows a simple pipeline (resulting in only a single call to `write(2)` and
172a single call to `write(2)`):
173
174 redisReply *reply;
175 redisAppendCommand(context,"SET foo bar");
176 redisAppendCommand(context,"GET foo");
177 redisGetReply(context,&reply); // reply for SET
178 freeReplyObject(reply);
179 redisGetReply(context,&reply); // reply for GET
180 freeReplyObject(reply);
181
182This API can also be used to implement a blocking subscriber:
183
184 reply = redisCommand(context,"SUBSCRIBE foo");
185 freeReplyObject(reply);
186 while(redisGetReply(context,&reply) == REDIS_OK) {
187 // consume message
188 freeReplyObject(reply);
189 }
190
191## Asynchronous API
192
193Hiredis comes with an asynchronous API that works easily with any event library.
194Examples are bundled that show using Hiredis with [libev](http://software.schmorp.de/pkg/libev.html)
195and [libevent](http://monkey.org/~provos/libevent/).
196
197### Connecting
198
199The function `redisAsyncConnect` can be used to establish a non-blocking connection to
200Redis. It returns a pointer to the newly created `redisAsyncContext` struct. The `error` field
201should be checked after creation to see if there were errors creating the connection.
202Because the connection that will be created is non-blocking, the kernel is not able to
203instantly return if the specified host and port is able to accept a connection.
204
205 redisAsyncContext *c = redisAsyncConnect("127.0.0.1", 6379);
206 if (c->error != NULL) {
207 printf("Error: %s\n", c->error);
208 // handle error
209 }
210
211The asynchronous context can hold a disconnect callback function that is called when the
212connection is disconnected (either because of an error or per user request). This function should
213have the following prototype:
214
215 void(const redisAsyncContext *c, int status);
216
217On a disconnect, the `status` argument is set to `REDIS_OK` when disconnection was initiated by the
218user, or `REDIS_ERR` when the disconnection was caused by an error. When it is `REDIS_ERR`, the `error`
219field in the context can be accessed to find out the cause of the error.
220
221The context object is always free'd after the disconnect callback fired. When a reconnect is needed,
222the disconnect callback is a good point to do so.
223
224Setting the disconnect callback can only be done once per context. For subsequent calls it will
225return `REDIS_ERR`. The function to set the disconnect callback has the following prototype:
226
227 int redisAsyncSetDisconnectCallback(redisAsyncContext *ac, redisDisconnectCallback *fn);
228
229### Sending commands and their callbacks
230
231In an asynchronous context, commands are automatically pipelined due to the nature of an event loop.
232Therefore, unlike the synchronous API, there is only a single way to send commands.
233Because commands are sent to Redis asynchronously, issuing a command requires a callback function
234that is called when the reply is received. Reply callbacks should have the following prototype:
235
236 void(redisAsyncContext *c, void *reply, void *privdata);
237
238The `privdata` argument can be used to curry arbitrary data to the callback from the point where
239the command is initially queued for execution.
240
241The functions that can be used to issue commands in an asynchronous context are:
242
243 int redisAsyncCommand(
244 redisAsyncContext *ac, redisCallbackFn *fn, void *privdata,
245 const char *format, ...);
246 int redisAsyncCommandArgv(
247 redisAsyncContext *ac, redisCallbackFn *fn, void *privdata,
248 int argc, const char **argv, const size_t *argvlen);
249
250Both functions work like their blocking counterparts. The return value is `REDIS_OK` when the command
251was successfully added to the output buffer and `REDIS_ERR` otherwise. Example: when the connection
252is being disconnected per user-request, no new commands may be added to the output buffer and `REDIS_ERR` is
253returned on calls to the `redisAsyncCommand` family.
254
255If the reply for a command with a `NULL` callback is read, it is immediately free'd. When the callback
256for a command is non-`NULL`, it is responsible for cleaning up the reply.
257
258All pending callbacks are called with a `NULL` reply when the context encountered an error.
259
260### Disconnecting
261
262An asynchronous connection can be terminated using:
263
264 void redisAsyncDisconnect(redisAsyncContext *ac);
265
266When this function is called, the connection is **not** immediately terminated. Instead, new
267commands are no longer accepted and the connection is only terminated when all pending commands
268have been written to the socket, their respective replies have been read and their respective
269callbacks have been executed. After this, the disconnection callback is executed with the
270`REDIS_OK` status and the context object is free'd.
271
272### Hooking it up to event library *X*
273
274There are a few hooks that need to be set on the context object after it is created.
275See the `adapters/` directory for bindings to *libev* and *libevent*.
276
277## Reply parsing API
278
279To be done.
280
281## AUTHORS
282
283Hiredis was written by Salvatore Sanfilippo (antirez at gmail) and
284Pieter Noordhuis (pcnoordhuis at gmail) and is released under the BSD license.