gpt4 book ai didi

c - 使用 hiredis 将带有空格的多词字符串推送到 redis

转载 作者:IT王子 更新时间:2023-10-29 06:11:59 25 4
gpt4 key购买 nike

我正在尝试将一个多词字符串推送到一个 Redis 键但是每个词都被添加为一个新元素我怎样才能避免这种情况

  #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <hiredis.h>

int main(int argc, char **argv) {
redisContext *c;
redisReply *reply;
int j;
struct timeval timeout = { 1, 500000 }; // 1.5 seconds
c = redisConnectWithTimeout("192.168.77.101",6379, timeout);
reply = redisCommand(c,"DEL mylist");
freeReplyObject(reply);
reply = redisCommand(c,"RPUSH mylist element 0"); freeReplyObject(reply);
reply = redisCommand(c,"RPUSH mylist element 1"); freeReplyObject(reply);
reply = redisCommand(c,"RPUSH mylist element 2"); freeReplyObject(reply);

reply = redisCommand(c,"LRANGE mylist 0 -1");
if (reply->type == REDIS_REPLY_ARRAY) {
for (j = 0; j < reply->elements; j++) {
printf("%u) %s\n", j, reply->element[j]->str);
}
}
freeReplyObject(reply);
redisFree(c);
return 0;
}

我希望响应是 3 个值,但我得到 6 个值

最佳答案

嗯,这是预期的行为。您应该使用参数占位符来构建命令。请看一下 documentation .

摘自 hiredis 源码:

/* Format a command according to the Redis protocol. This function
* takes a format similar to printf:
*
* %s represents a C null terminated string you want to interpolate
* %b represents a binary safe string
*
* When using %b you need to provide both the pointer to the string
* and the length in bytes. Examples:
*
* len = redisFormatCommand(target, "GET %s", mykey);
* len = redisFormatCommand(target, "SET %s %b", mykey, myval, myvallen);
*/

如果您按如下方式更改代码,它将解决问题。

reply = redisCommand(c,"RPUSH mylist %s","element 0"); freeReplyObject(reply);
reply = redisCommand(c,"RPUSH mylist %s","element 1"); freeReplyObject(reply);
reply = redisCommand(c,"RPUSH mylist %s","element 2"); freeReplyObject(reply);

此外,我建议系统地测试 hiredis API 的返回码。这可能很麻烦,但会在项目的后期阶段为您省去很多问题。

关于c - 使用 hiredis 将带有空格的多词字符串推送到 redis,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20067653/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com