安装redis
- 首先在服务器上安装redis,具体过程参照reids官网,最简单的方法就是
curl -fsSL https://packages.redis.io/gpg | sudo gpg --dearmor -o /usr/share/keyrings/redis-archive-keyring.gpg
echo "deb [signed-by=/usr/share/keyrings/redis-archive-keyring.gpg] https://packages.redis.io/deb $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/redis.list
sudo apt-get update
sudo apt-get install redis
- 或者根据官网源码安装
启动redis-server
- 如果是默认config,直接在命令行中输入
redis-server
。 - 如果需要自己设定config,则在命令行中输入
redis-server /path/to/redis.config
(config文件在redis源文件中有) - 启动以后就是这样
- 有时候可能端口6379被占用,可以通过命令
lsof -i:6379
查看端口占用情况,或者通过命令netstat -tunlp | grep 6379
,并用sudo kill -9 进程PID
杀掉该进程。
使用redis-cli测试
可以用redis-cli中的命令行测试是否能正常于redis-server连接。我用了以下命令:
redis-cli
keys *
PING
结果如下
下载并编译hiredis
- 首先下载hiredis的github地址
git clone https://github.com/redis/hiredis.git
- 编译和安装
make
make install
- 安装完成后,在hiredis目录下得到libhiredis.so
在destor中使用hiredis连接redis
- 首先尝试连接redis,可以新建一个.c文件,里面写连接redis和向redis发送命令的函数,这里写出一个连接redis的示例。其中hostname是127.0.0.1,是因为我的客户端和服务器都在同一个服务器上,就是本机地址,端口是redis的默认端口6379。
int example3() {
unsigned int j;
redisContext *conn;
redisReply *reply;
redisReply *reply2;
const char *hostname = "127.0.0.1";
const int port = 6379;
const char *password = "";
struct timeval timeout = { 1, 500000 }; // 1.5 seconds
conn = redisConnectWithTimeout(hostname, port, timeout);
if (conn == NULL || conn->err) {
if (conn) {
printf("Connection error: %s\n", conn->errstr);
redisFree(conn);
}
else {
printf("Connection error: can't allocate redis context\n");
}
exit(1);
}
/* AUTH */
// printf("connected\n");
reply2 = (redisReply*) redisCommand(conn, "PING", "Hello");
// printf("%s\n", reply2->str);
printf("connected\n");
//reply = redisCommand(conn, "AUTH %s", password);
//printf("AUTH: %s\n", reply->str);
// freeReplyObject(reply2);
/* Set */
reply = redisCommand(conn,"SET %s %s", "welcome", "Hello, DCS for Redis!");
printf("SET: %s\n", reply->str);
freeReplyObject(reply);
/* Get */
reply = redisCommand(conn,"GET welcome");
printf("GET welcome: %s\n", reply->str);
freeReplyObject(reply);
/* Disconnects and frees the context */
redisFree(conn);
return 0;
}
- 修改CMakeList.txt
...
include_directories(/home/xh21/hiredis)
...
target_link_libraries(destor hiredis glib-2.0 pthread ssl crypto isal_crypto rocksdb)
- 然后就
cmake ..
然后make
,都完全没问题
- 跑的时候就发现问题了,程序会卡在这里,并且任何的redisCommand都无法发出去,它会一直卡在等待server回复的函数里。
reply2 = (redisReply*) redisCommand(conn, "PING", "Hello");
经过各种测试,发现是hiredis中的sds.c和destor中的/utils/sds.c冲突了,并且destor中的sds.c和hiredis中的sds.c中函数名相同,但是定义不同,hiredis中使用sds中函数时,跑到destor里的函数里去了,就卡住了。
最终的解决方案就是统一两个项目sds.c和sds.h文件,把hiredis中的sds.c和sds.h拷贝到destor中去,就可以跑起来了。