ZBLOG

redis c语言demo

以下是一个简单的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库。

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=139

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?