开发者

App Engine Datastore - Incrementing property increments by 2

I'm trying to build out a simple app engine datastore entity that basically keeps count of how many times it was viewed. I've got the code setup in a JSP file that does increment the variable, however every time it seems to increment by 2 rather than one. Here's the code in question.

    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    Entity story开发者_Go百科 = datastore.get(KeyFactory.stringToKey(request.getParameter("story_key")));
    String json_out = "";

    int num_views = 0;
    if(story.getProperty("views") != null) {
        num_views = Integer.parseInt(story.getProperty("views").toString());
    }
    //Update the donated status of this object.
    story.setProperty("views", num_views + 1);
    datastore.put(story);

    json_out += "{";
    json_out += "\"title\":\"" + story.getProperty("title") + "\", ";
    json_out += "\"views\":\"" + num_views + "\"";
    json_out += "}";

    out.println(json_out);

Any idea why it would be incrementing by 2? I've even tried subtracting one when I get the number of views, but then the number just stays the same all the time as you'd expect. Really odd.


If you are implementing a counter using the datastore, you should you techniques that allow for high throughput. Your solution above could easily write to the datastore more than a few times per second, violating HRD policies. Also, it's not thread safe (not run in a transaction, so updates could apply out of order and your result is not what you expect). Try out shard counters, which fix these issues:

http://code.google.com/appengine/articles/sharding_counters.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜