【问题标题】:How to store variables in Google Cloud Platform如何在 Google Cloud Platform 中存储变量
【发布时间】:2016-12-05 17:44:14
【问题描述】:

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

我的 POST 路由设置了 /display-message 使用的 new_posted_time 变量:

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

【问题讨论】:

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


    【解决方案1】:

    您可能应该将这样的“状态”存储在像Google Cloud Datastore 这样的持久存储中。这是一篇关于 implementing counters 与 Google Cloud Datastore 的文章(它来自 AppEngine Datastore API,但原理相同)。

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

    【讨论】:

    • 如果我将变量作为实体存储在数据存储中,这与在我的实例中存储状态相同吗?如果是,那么存储共享变量最有效/最合适的方法是什么?
    • 不使用数据存储与“在实例中存储状态”不同。不同之处在于,当您使用数据存储时,您正在使用始终可用的服务将数据写入磁盘,当您写入共享变量时,您正在将数据存储在内存中,在自动缩放器可以任意关闭的机器实例上。
    • 谢谢!我对如何在我的代码中实现谷歌数据存储有点困惑。我在 Node.js 中看到了几种方法可以做到这一点,但无法让它发挥作用。
    猜你喜欢
    • 2020-10-03
    • 1970-01-01
    • 1970-01-01
    • 2016-04-08
    • 1970-01-01
    • 2021-05-05
    • 1970-01-01
    • 1970-01-01
    • 2019-10-12
    相关资源
    最近更新 更多