2016-01-06 84 views
0

我最近在我的一個C++程序中包含了一個redis連接。我決定使用redox庫,因爲它看起來很容易使用,並且不依賴於boost庫。關於退貨類型的Redis錯誤

我使用連接將值插入到redis中的列表中。該命令在大多數情況下都能正常工作,但有時會出現一條錯誤消息,說明Received reply of type 3, expected type 1 or 5.經過大量搜索後,我在hiredis.h頭文件中發現了這些返回類型。看起來圖書館期待StringStatus答覆類型,但收到Integer類型。

不幸的是,我還無法找到任何有關這意味着什麼以及如何解決問題的信息。特別是這些代碼有時起作用,有時不會讓我感到困惑。

在我的使用案例中,我將一個包含json字典的字符串值以celery格式(但基本上只是一個字符串)插入到列表中。我非常肯定,它與字符串的組成方式無關,因爲通過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()檢查後的一個。

謝謝你的幫助。

回答

1

您所遇到的問題是由於您將字符串用作響應的參數。

正如documentation of redox提到:

此語句告訴氧化還原運行命令Get打招呼。該<string>模板參數意味着我們希望回答被放入一個字符串,我們希望服務器的東西,可以放入一個字符串

響應但是,可行的,因爲例子用的是「GET 「預期會返回一個字符串的命令。在您使用返回結果的「LPUSH」命令的情況下,也是整數能發行使用Redis的-CLI

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

所以,你必須使用一個整數參數的響應命令時可以看出,由於上市here可能響應的完整列表是:

<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; 
} 

,或者在使用LAMDA:

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; 
} 
+0

謝謝。你是對的,我沒有考慮任何回報價值,因爲它並沒有真正吸引我。 – Tim