Created
November 8, 2011 16:23
-
-
Save zigorou/1348238 to your computer and use it in GitHub Desktop.
connect to redis by hiredis
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdio.h> | |
| #include <stdlib.h> | |
| #include <unistd.h> | |
| #include <hiredis/hiredis.h> | |
| /** | |
| * gcc -I/usr/local/include -L/usr/local/lib -lhiredis -Wall -o connect connect.c | |
| */ | |
| void redisDisconnect(redisContext *ctx) { | |
| close(ctx->fd); | |
| redisFree(ctx); | |
| } | |
| void displayRedisReply(redisReply *reply) { | |
| switch (reply->type) { | |
| case REDIS_REPLY_STATUS: | |
| printf("type: REDIS_REPLY_STATUS\n"); | |
| printf("length: %d. str: %s\n", reply->len, reply->str); | |
| break; | |
| case REDIS_REPLY_ERROR: | |
| printf("type: REDIS_REPLY_ERROR\n"); | |
| break; | |
| case REDIS_REPLY_INTEGER: | |
| printf("type: REDIS_REPLY_INTEGER\n"); | |
| break; | |
| case REDIS_REPLY_NIL: | |
| printf("type: REDIS_REPLY_NIL\n"); | |
| break; | |
| case REDIS_REPLY_STRING: | |
| printf("type: REDIS_REPLY_STRING\n"); | |
| break; | |
| case REDIS_REPLY_ARRAY: | |
| printf("type: REDIS_REPLY_ARRAY\n"); | |
| break; | |
| default: | |
| break; | |
| } | |
| } | |
| int main(int argc, char *argv[]) { | |
| redisContext *ctx; | |
| redisReply *reply; | |
| ctx = redisConnect("127.0.0.1", 6379); | |
| if (ctx->err) { | |
| printf("Error: %s\n", ctx->errstr); | |
| exit(-1); | |
| } | |
| reply = redisCommand(ctx, "PING"); | |
| displayRedisReply(reply); | |
| freeReplyObject(reply); | |
| reply = redisCommand(ctx, "SET foo %s", "bar"); | |
| displayRedisReply(reply); | |
| freeReplyObject(reply); | |
| reply = redisCommand(ctx, "GET %s", "foo"); | |
| displayRedisReply(reply); | |
| freeReplyObject(reply); | |
| redisDisconnect(ctx); | |
| exit(0); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Is it correct code? In MS VS I have access violation at 19th line, when I try to get string and length from object reply. In debug reply->str and reply->len have correct varibales.