C 调用redis缓冲

下载 redis 文件, 进行编译  

  wget https://github.com/redis/hiredis/archive/master.zip

    将其解压, 并编译

    unzip -x  master.zip

    make && make install

加载进行简单测试:
redis-server 加载redis.conf  配置文件 
发现c程序执行命令为 get foo   ;; 可以将redid-cli  连接进入  keys * ; set foo 12 
发现程序运行之后 取出数据 为foo  —> 12 说明运行正确;
  
testredis.c

#include <stdio.h>
#include <stdlib.h>
#include <hiredis/hiredis.h>

/*
* 请求 redis网络缓存服务器内存.
*/

int main(int argc, char* argv[]) {
    redisContext *conn = redisConnect("127.0.0.1", 6379);
    if(NULL == conn) {
        fprintf(stderr, "redisConnect 127.0.0.1:6379 error!\n");
        exit(EXIT_FAILURE);
    }   
    if(conn->err) {
        fprintf(stderr, "redisConect error:%d\n", conn->err);
        redisFree(conn);
        exit(EXIT_FAILURE);
    }   

    // 这里redisConnect 链接对象创建完毕了
    redisReply *reply = redisCommand(conn, "get foo");
    if(reply && reply->type == REDIS_REPLY_STRING) {
        printf("get foo => %s\n", reply->str);
    }   
    printf("reply->type = %d\n", reply->type);

    // 释放这个对象
    freeReplyObject(reply);
    // 释放hiredis 上下文对象   
    redisFree(conn);

    return 0;
}

    

  

Makefile 文件编译;
 
testredis:testredis.c
     gcc -g -Wall -o  testredis testredis.c -lhiredis 

 

make && ./testredis 

查看结果;

 

posted @ 2016-12-25 16:02  Rocky_Ansi  阅读(480)  评论(0编辑  收藏  举报