概述
项目中使用到了Redis作为实时库,故安装了对应的Linux C开发库。
下载路径:https://github.com/redis/hiredis
安装
- 安装
unzip hiredis-master.zip
cd hiredis-master
make
make install
# 可以看到,hiredis安装到了/usr/local/lib和/usr/local/include下
- 添加动态库寻找路径
vim /etc/ld.so.conf
在文件最后新增一行添加:
/usr/local/lib
因为系统默认不寻找/usr/local/lib目录下的动态连接库。
然后执行:
ldconfig
使之生效。
测试
vim test_hiredis.c
#include <stdio.h>
#include <string.h>
#include <hiredis/hiredis.h>
int main()
{
redisContext *pRedisCtx = redisConnect("127.0.0.1", 6379);
if (pRedisCtx->err)
{
redisFree(pRedisCtx);
printf("Connect redis server err: %s\n", pRedisCtx->errstr);
return -1;
}
printf("Connect redis server success...\n");
const char *cmdSetVal = "SET test 100";
redisReply *pReply = (redisReply *)redisCommand(pRedisCtx, cmdSetVal);
if (NULL == pReply)
{
printf("Command[ %s ] exec failed!\n", cmdSetVal);
redisFree(pRedisCtx);
return -1;
}
if (!(pReply->type == REDIS_REPLY_STATUS && strcmp(pReply->str, "OK") == 0))
{
printf("Command[ %s ] exec failed!\n", cmdSetVal);
freeReplyObject(pReply);
redisFree(pRedisCtx);
return -1;
}
freeReplyObject(pReply);
printf("Command[ %s ] exec success...\n", cmdSetVal);
const char *cmdGetVal = "GET test";
pReply = (redisReply *)redisCommand(pRedisCtx, cmdGetVal);
if (pReply->type != REDIS_REPLY_STRING)
{
printf("Command[ %s ] exec failed!\n", cmdGetVal);
freeReplyObject(pReply);
redisFree(pRedisCtx);
return -1;
}
printf("GET test: %s\n", pReply->str);
freeReplyObject(pReply);
redisFree(pRedisCtx);
}
gcc test_hiredis.c -lhiredis
./a.out