1)启动redis
# 启动redis服务---redis默认端口6379
redis-server redis.conf
2)测试redis连通性
# 连接6379端口,set和get分别设置和获取键值
[root@192 /usr/local/bin]$redis-cli -p 6379
127.0.0.1:6379> set ttt 123
OK
127.0.0.1:6379> get ttt
"123"
127.0.0.1:6379> keys *
1) "ttt"
3)hiredis下载和安装
hiredis下载地址:https://github.com/redis/hiredis
# 下载安装包并解压
unzip hiredis-master.zip
# 编译、安装
cd hiredis-master
make
make install
4)查看hiredis是否安装成功
# 进入/usr/local/lib下查看是否有hiredis相关库
libhiredis.a
libhiredis.so
libhiredis.so.1.1.1-dev
# 进入/usr/local/include下查看是否有相应头文件
[root@192 hiredis]# ls
adapters alloc.h async.h hiredis.h read.h sds.h sockcompat.h
[root@192 hiredis]# pwd
/usr/local/include/hiredis
5)测试
a)创建测试文件my_hiredis.c
touch my_hiredis.c
b)编写测试程序
vim my_hiredis.c
c)测试代码
#include <stdio.h>
#include <string.h>
#include <hiredis/hiredis.h>
int main()
{
// 1. 连接redis数据库
redisContext *ctx = redisConnect("127.0.0.1", 6379);
if (ctx->err)
{
redisFree(ctx);
printf("Connect redis server err: %s\n", ctx->errstr);
return -1;
}
printf("Connect redis server success...\n");
// 2. redis操作命令: 设置值
const char *cmdSetVal = "SET dong 10";
redisReply *reply = (redisReply *)redisCommand(ctx, cmdSetVal);
if (NULL == reply)
{
printf("Command[ %s ] exec failed!\n", cmdSetVal);
redisFree(ctx);
return -1;
}
// 3. redis返回值判断
if (!(reply->type == REDIS_REPLY_STATUS && strcmp(reply->str, "OK") == 0))
{
printf("Command[ %s ] exec failed!\n", cmdSetVal);
freeReplyObject(reply);
redisFree(ctx);
return -1;
}
// 4. 内存释放
freeReplyObject(reply);
printf("Command[ %s ] exec success...\n", cmdSetVal);
// 5. redis操作命令: 获取值
const char *cmdGetVal = "GET test";
reply = (redisReply *)redisCommand(ctx, cmdGetVal);
// 6. redis返回值判断
if (reply->type != REDIS_REPLY_STRING)
{
printf("Command[ %s ] exec failed!\n", cmdGetVal);
freeReplyObject(reply);
redisFree(ctx);
return -1;
}
printf("GET dong: %s\n", reply->str);
freeReplyObject(reply);
redisFree(ctx);
}
d)编译运行
# 编译
gcc my_hiredis.c -o my_hiredis -lhiredis
# 运行
[root@192 project]# ./my_hiredis
Connect redis server success...
Command[ SET dong 10 ] exec success...
GET test: 10
[root@192 project]#