以下是一个简单的Redis C语言Demo:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "hiredis.h"
int main(int argc, char **argv) {
redisContext *c;
redisReply *reply;
const char *hostname = "127.0.0.1";
int port = 6379;
struct timeval timeout = { 1, 500000 };
c = redisConnectWithTimeout(hostname, port, timeout);
if (c == NULL || c->err) {
if (c) {
printf("Connection error: %s\n", c->errstr);
redisFree(c);
} else {
printf("Connection error: can't allocate redis context\n");
}
exit(1);
}
// set a key-value pair
reply = redisCommand(c, "SET %s %s", "foo", "bar");
printf("SET: %s\n", reply->str);
freeReplyObject(reply);
// get the value of a key
reply = redisCommand(c, "GET %s", "foo");
printf("GET: %s\n", reply->str);
freeReplyObject(reply);
// increment the value of a key
reply = redisCommand(c, "INCR %s", "counter");
printf("INCR: %lld\n", reply->integer);
freeReplyObject(reply);
// get all keys in the database
reply = redisCommand(c, "KEYS *");
if (reply->type == REDIS_REPLY_ARRAY) {
for (int i = 0; i < reply->elements; i++) {
printf("%d) %s\n", i+1, reply->element[i]->str);
}
}
freeReplyObject(reply);
redisFree(c);
return 0;
}
这个Demo连接到本地Redis实例,设置一个key-value对,获取一个key的值,将另一个key的值递增1,并获取所有数据库中的键名。需要安装hiredis库。