2016-12-05 113 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中执行此操作的方法,但无法使其工作。 –

相关问题