在使用Redis客户端hiredis处理redis的命令时,当key或者value中包括空格时,遇到命令执行失败的问题。
具体情况如下:
#include <hiredis/hiredis.h>
int main(int argc, char const *argv[])
{
redisContext *c = redisConnect("127.0.0.1", 6379);
if (c != NULL && c->err) {
printf("Error: %s\n", c->errstr);
}
redisReply *reply;
// 执行命令: SET foo "bar bar"
// 直接使用字符串拼接会执行错误
reply = redisCommand(c, "SET foo \"bar bar\"");
if (reply->type == REDIS_REPLY_ERROR) {
printf("Error - 1: %s\n", reply->str);
}
// 通过%s代替后可以正确执行
reply = redisCommand(c, "SET foo %s", "bar bar");
if (reply->type == REDIS_REPLY_ERROR) {
printf("Error - 2: %s\n", reply->str);
}
return 0;
}
程序的执行结果如下:
roo@roose:~/myredis$ cc hitest.c -lhiredis
roo@roose:~/myredis$ ./a.out
Error - 1: ERR syntax error