2011-11-22 28 views
1

我做了一些node.js代碼來檢索redis數據庫中的數據,但我並不真的很高興,我想改進它...
基本上,我在我的redis db中創建了一個「人員」。從「人」我得到一個「人:我」(我是一個整數)的列表,併爲每個「人:我」,我做了一個額外的查詢來檢索密鑰「人:我」的散列。在node.js中執行多個redis查詢的更清潔的方法

這是我要做的事:

db.smembers("people", function(err1, people){ 
    var jsonObj; 
    var jsonArr = []; 
    if(!err1) { 
    var i = 0; 
    res.writeHead(200, {'content-type': 'application/json'}); 
    // people will provide a list like [person:1, person:2, ..., person:n] 
    people.forEach(function(person){ 
     // In redis I get the hash with key "person:i" 
     db.hgetall(person, function(err2,obj){ 
     if(!err2){ 
      // Add person into array 
      jsonArr.push({ "id" : person.substring(7), "lastname" : obj["lastname"], "firstname" : obj["firstname"]}); 

      // I'm not happy with this part where I check if I reached the last item of people array.... 
      i = i + 1; 
      if(i == people.length){ 
      res.write(JSON.stringify(jsonArr)); 
      res.end(); 
      } 
     } else { 
      var jsonObj = { "error" : "database error", "message" : "Cannot get hash " + person}; 
      res.write(JSON.stringify(jsonObj)); 
      res.end(); 
     } 
     }); 
    }); 
    } else { 
    jsonObj = { "error" : "database error", "message" : err1.message }; 
    res.writeHead(200, {'content-type': 'application/json'}); 
    res.write(JSON.stringify(jsonObj)); 
    res.end(); 
    } 
}); 

什麼是最乾淨的(至少清潔)的方式來做到這一點?

回答

4

您正在尋找的是異步控制流程系統。一個例子是Stepstreamline.js

另一種方法是抽象過程,爲將要獲取個人對象的Person創建一個數據模型,以及一個人員模型,該人員模型是一個人員集合,其中包括一個用於獲取多個人的方法,重新使用。

編輯:我發現節點兼容的控制流/異步庫的全面上市:https://github.com/joyent/node/wiki/modules#wiki-async-flow

編輯:審查您的代碼後,我以爲這是相當具體到本案另一種替代方法但並不直接解決問題的控制流性質。

通過更改您的模式以僅存儲people密鑰中的人員ID,您可以使用redis的SORT命令打開自己,這將使整個集合能夠在單個命令中獲取。要在Redis的做到這一點:

> SADD people 1 2 3 4 
> HMSET person:1 firstname John lastname Smith 
> HMSET person:2 firstname Jane lastname Smith 
> HMSET person:3 firstname John lastname Doe 
> HMSET person:4 firstname Jane lastname Doe 
> SORT people GET # GET person:*->firstname GET person:*->lastname 
1) "1" 
2) "Jane" 
3) "Doe" 
4) "2" 
5) "Jane" 
6) "Smith" 
7) "3" 
8) "John" 
9) "Doe" 
10) "4" 
11) "Jane" 
12) "Doe" 

這已在people密鑰存儲器節省額外的好處,並且能夠分頁/通過SORT命令的bylimit選項排序。

+0

感謝您的建議。事情是我現在無法輕鬆修改架構。我在node.js中更多地尋找流量控制的最佳實踐,因爲我有幾個地方需要更清晰的代碼。非常感謝您的幫助(我會明確地看看您描述的解決方法)。 – Luc

+0

感謝您的回答!它允許我找出最適合我的方式:)'排序消息desc limit 0 10獲得消息:* - > text'獲取最後10條消息。 –