简体   繁体   中英

How to store variables in Google Cloud Platform

How can I store a variable in Google Cloud Platform? Right now I am using a global variable that my routes share, but the values are off every time a request has been made to the route. I think it's because my server may have multiple instances running sharing the same variable. My application is using Node.js/Express.

My POST route sets the new_posted_time variable that /display-message uses:

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>");

});

My GET route gets the value for new_posted_time that was defined in /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();

});

So I need to be able to store the shared variable new_posted_time somewhere in Google's database because the value is not consistent every time my application runs due to many instances running (which is my guess).

You should probably store 'state' like this in a persistent store like Google Cloud Datastore . Here is an article on implementing counters with Google Cloud Datastore (its from the AppEngine Datastore API, but it is the same principle).

Storing state in your instances is a bad idea because not only will you have consistency problems between instances, you will also lose data when an instance is shutdown automatically by AppEngine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM