Redis接口的调用

Posted Andy Niu ----程序,篮球,羽毛球,科普

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Redis接口的调用相关的知识,希望对你有一定的参考价值。

1、hiredis是redis数据库的C接口,目录为/redis-3.2.6/deps/hiredis
2、示例代码如下:
    #include <stdio.h>
    #include <stdlib.h>
    #include <stddef.h>
    #include <stdarg.h>
    #include <string.h>
    #include <assert.h>
    #include "hiredis.h"
    
    int main()
    {
        //连接redis
        redisContext* c = redisConnect("127.0.0.1", 6379);
        if ( c->err)
        {
            redisFree(c);
            printf("Connect to redisServer faile\n");
            return -1;
        }
        printf("Connect to redisServer Success\n");
        
        const char* setCommand = "set name andy";
        redisReply* r = (redisReply*)redisCommand(c, setCommand);
        
        if( NULL == r)
        {
            printf("Execut setCommand failure\n");
            redisFree(c);
            return -1;
        }
        if( !(r->type == REDIS_REPLY_STATUS && strcasecmp(r->str,"OK")==0))
        {
            printf("Failed to execute command[%s]\n",setCommand);
            freeReplyObject(r);
            redisFree(c);
            return -1;
        }
        freeReplyObject(r);
        printf("Succeed to execute command[%s]\n", setCommand);
        
        
        const char* getCommand = "get name";
        r = (redisReply*)redisCommand(c, getCommand);
        if ( r->type != REDIS_REPLY_STRING)
        {
            printf("Failed to execute command[%s]\n",getCommand);
            freeReplyObject(r);
            redisFree(c);
            return -1;
        }
        printf("Succeed to execute command[%s]\n", getCommand);
        printf("The value of ‘name‘ is %s\n", r->str);
        freeReplyObject(r);
        
        redisFree(c);
        return 0;
    }
3、编译,运行如下:
    [[email protected] hiredis]# g++ -o main main.cpp libhiredis.a
    [[email protected] hiredis]# ./main
    Connect to redisServer Success
    Succeed to execute command[set name andy]
    Succeed to execute command[get name]
    The value of ‘name‘ is andy

以上是关于Redis接口的调用的主要内容,如果未能解决你的问题,请参考以下文章

Aop+Redis防止接口重复提交

实战服务调用幂等性:Spring Boot 集成 Redis

Redis令牌桶算法(全网最全,后续可以接入lua做原子性操作)

技术干货 | 高负载压测下接口异常问题定位排查-Redis

Redis 计数器

Filter+Redis解决项目之间调用的幂等性