2016-12-05 114 views
0

如何在Google雲端平臺中存儲變量?現在我正在使用我的路由共享的全局變量,但每次對路由發出請求時,這些值都會關閉。我認爲這是因爲我的服務器可能有多個實例共享相同的變量。我的應用程序正在使用Node.js/Express。如何在Google雲端平臺中存儲變量

我的帖子路線設置new_posted_time變量/display-message用途:

var new_posted_time = 0; 
app.post('/message', function (request, response) { 
    message = request.body.Body; 

    new_posted_time = new_posted_time + 1; 

    console.log("This is the new time from POST: " + new_posted_time); 
    response.send("<Response><Message>Heyyo!</Message></Response>"); 

}); 

我GET途徑獲取/message定義,對於new_posted_time值。

app.get('/display-message', function(req,res){ 

    var last_updated_time = req.query.last_updated; 

    function checkMessage() { 
     var new_time = new_posted_time; 
     console.log("Checking messaged with new time from GET: " + new_time); 

     if(!last_updated_time || last_updated_time < new_time) { 
      updateMessage(new_time); 
     } 
     else { 
      console.log("No new messages at this time"); 
      myTimeout = setTimeout(function(){ 
       checkMessage(res); 
      }, 1000 * 10); //10 seconds 
     } 
    } 

    function updateMessage() { 
     console.log("Updating message now"); 
     var output = { 
      success: 1, 
      data: message, 
      old_stamp: last_updated_time, 
      new_stamp: new_stamp 
     }; 

     return res.json(output); 
    } 

    checkMessage(); 

}); 

所以我需要能夠在一些地方保存共享變量new_posted_time在谷歌的數據庫,因爲該值是不相符的,每次我的應用程序運行時,由於運行許多情況下(這是我的猜測)。

回答

0

您應該像這樣在像Google Cloud Datastore這樣的持久存儲中存儲'狀態'。這裏有一篇關於implementing counters與Google Cloud Datastore(它來自AppEngine Datastore API,但原理相同)的文章。

在您的實例中存儲狀態是一個壞主意,因爲您不僅會遇到實例之間的一致性問題,還會在AppEngine自動關閉實例時丟失數據。

+0

如果我將變量作爲實體存儲在數據存儲中,那麼和我的實例中存儲狀態是否一樣?如果是,那麼存儲共享變量的最有效/最合適的方法是什麼? –

+0

不使用數據存儲與「在您的實例中存儲狀態」不同。不同之處在於,當您使用一種服務將數據寫入磁盤時,數據存儲區將始終可用,當您將存儲數據的共享變量寫入到可由Autoscaler任意關閉的機器實例中時。 –

+0

謝謝!我有點困惑於如何在我的代碼中實現谷歌數據存儲。我看到了幾種在Node.js中執行此操作的方法,但無法使其工作。 –

相關問題