如何在Google Cloud Platform中存储变量

时间:2016-12-05 17:44:15

标签: node.js google-app-engine express

如何在Google云端平台中存储变量?现在我正在使用我的路由共享的全局变量,但每次向路由发出请求时,值都会关闭。我认为这是因为我的服务器可能有多个实例共享同一个变量。我的应用程序使用的是Node.js / Express。

我的POST路由设置了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路线获取new_posted_time中定义的/message的值。

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存储在Google数据库的某个地方,因为每次我的应用程序运行时,由于许多实例运行(这是我的猜测),该值不一致。

1 个答案:

答案 0 :(得分:0)

你应该将这样的'state'存储在像Google Cloud Datastore这样的持久存储中。以下是有关Google云数据存储的implementing counters的文章(来自AppEngine数据存储区API,但原理相同)。

在您的实例中存储状态是个坏主意,因为不仅实例之间会出现一致性问题,而且当AppEngine自动关闭实例时,您也会丢失数据。