0

我正在使用hiredis库的redisCommand来做这样的事情:

LPUSH list1 a b "" c d "" e

其中“”表示我想在列表中插入空元素。当我从 redis 上的命令行执行此操作时,它工作正常,但是当我将其作为命令传递给hiredis 时,它不起作用并且元素最终是“”而不是空的。有什么解决办法吗?

这是我调用 redisCommand 的方式:

reply = (redisReply *) redisCommand(c,"LPUSH list1 a b c "" c d "" e);

我也试过放单引号、反斜杠等

4

2 回答 2

0

您可以在 Redis 中使用二进制安全字符串。继续使用 LPUSH 命令将二进制字符串添加到您的列表中,如下所示:

redisReply *reply = redisCommand(context, "LPUSH list1 %b %b %b", "a", strlen("a"), "", 0, "b", strlen("b"));

输出将是:

127.0.0.1:6379> lrange list1 0 -1
1) "b"
2) ""
3) "a"

HTH,斯旺南德

于 2017-03-10T07:24:31.613 回答
0

如果要推送到列表的元素数量是固定的:redisCommand与格式化参数一起使用

const char *list = "list-name";
const char *non_empty_val = "value";
const char *empty_val = "";
/* or use %b to push binary element, as the other answer mentioned. */
redisReply *reply = (redisReply*)redisCommand(redis,
                          "lpush %s %s %s", list, non_empty_val, empty_val);

如果元素的数量是动态的:使用redisCommandArgv

int argc = 4;  /* number of arguments including command name. */

const char **argv = (const char**)malloc(sizeof(const char**) * argc);
argv[0] = strdup("lpush");
argv[1] = strdup(list);
argv[2] = strdup(non_empty_val);
argv[3] = strdup(empty_val);

/* specify the length of each argument. */
size_t *argv_len = (size_t*)malloc(sizeof(size_t) * argc);
for (int i = 0; i < argc; ++i)
    argv_len[i] = strlen(argv[i]);

redisReply *reply = (redisReply*)redisCommandArgv(redis, argc, argv, argv_len);
于 2017-03-10T07:52:18.770 回答