Redis关于返回类型的错误

Redis error about return type

本文关键字:错误 返回类型 Redis      更新时间:2023-10-16

我最近在一个c++程序中包含了一个redis连接。我决定使用氧化还原库,因为它看起来很容易使用,而且不依赖于升压库。

我使用连接将值插入到redis中的列表中。该命令在大多数情况下都有效,但有时我会收到一条错误消息,说Received reply of type 3, expected type 1 or 5.经过广泛搜索,我在hiredis.h头文件中找到了这些返回类型。库似乎期望StringStatus回复类型,但接收到的是Integer类型。

不幸的是,我还没有找到任何关于这意味着什么以及如何解决问题的信息。尤其是代码有时有效,有时不会让我感到困惑。

在我的用例中,我将一个字符串值插入到一个列表中,该值包含一个芹菜格式的json字典(但本质上只是一个字符串)。我确信这与字符串的组成方式无关,因为通过redis-cli客户端手动插入相同的字符串效果良好。

我插入消息的代码是:

redox::Redox rdx;
try {
    if(!rdx.connect("localhost", 6379)){
        cerr << "Could not connect to redis" << endl;
    }
    redox::Command<string>& c = rdx.commandSync<string>({"lpush", "queue_name", message});
    if(!c.ok()) {
        cerr << "Error while communicating with redis" << c.status() << endl;
    }
} catch (runtime_error& e) {
    cerr << "send_message: Exception in redox: " << e.what() << endl;
}

打印的错误是!c.ok()检查之后的错误。

谢谢你的帮助。

您遇到的问题是因为您使用字符串作为响应的参数。

如氧化还原文件中所述:

此语句告诉氧化还原运行命令GET hello。<string>模板参数意味着我们希望将回复放入字符串中,并希望服务器使用可以放入字符串的内容进行响应

但这是有效的,因为该示例使用的是"GET"命令,该命令应返回一个字符串。在使用"LPUSH"命令的情况下,返回结果是一个整数,这可以在使用redis cli 发出命令时看到

127.0.0.1:6379> lpush "test" test
(integer) 1

所以你必须使用一个带有整数参数的响应,这里列出的可能响应的完整列表是:

<redisReply*>: All reply types, returns the hiredis struct directly
<char*>: Simple Strings, Bulk Strings
<std::string>: Simple Strings, Bulk Strings
<long long int>: Integers
<int>: Integers (careful about overflow, long long int recommended)
<std::nullptr_t>: Null Bulk Strings, any other receiving a nil reply will get a NIL_REPLY status
<std::vector<std::string>>: Arrays of Simple Strings or Bulk Strings (in received order)
<std::set<std::string>>: Arrays of Simple Strings or Bulk Strings (in sorted order)
<std::unordered_set<std::string>>: Arrays of Simple Strings or Bulk Strings (in no order)

这样的东西就可以了:

redox::Redox rdx;
try {
  if(!rdx.connect("localhost", 6379)){
    cerr << "Could not connect to redis" << endl;
  }
  redox::Command<int>& c = rdx.commandSync<int>({"lpush", "queue_name", message});
  if(!c.ok()) {
    cerr << "Error while communicating with redis" << c.status() << endl;
}}catch (runtime_error& e) {
    cerr << "send_message: Exception in redox: " << e.what() << endl;
}

或者如果使用λ:

redox::Redox rdx;
try {
  if(!rdx.connect("localhost", 6379)){
    cerr << "Could not connect to redis" << endl;
  }
  rdx.commandSync<int>(
    {"lpush", "queue_name", message},
    [](redox::Command<int>& response){
      if(!response.ok()){
        cerr << "Error while communicating with redis" << c.status() << endl;
  }});  
}catch (runtime_error& e) {
    cerr << "send_message: Exception in redox: " << e.what() << endl;
}