在使用Redis客户端hiredis处理redis的命令时,当key或者value中包括空格时,遇到命令执行失败的问题。 redis
具体状况以下: shell
#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; }
程序的执行结果以下: spa
roo@roose:~/myredis$ cc hitest.c -lhiredis roo@roose:~/myredis$ ./a.out Error - 1: ERR syntax error