我有一个简单的Web服务,它提供了两种方法:
addHighscore - 如果未达到MAX或得分高于最低条目,则向高分榜添加新条目
// check if free place in highscore
int count = ofy().load().type(Highscore.class)
.filter("difficulty", difficulty).count();
boolean insert = count + 1 < MAX;
if(insert == false) {
// get last element and free if possible
Highscore least = ofy().load().type(Highscore.class)
.filter("difficulty", difficulty).order("-score").order("-date")
.first().now();
if(highscore.getScore() > least.getScore()) {
ofy().delete().entity(least).now();
insert = true;
}
}
// insert
if(insert == true)
ofy().save().entity(highscore).now();
getHighscore - 获得高分
List<Highscore> list = ofy().load().type(Highscore.class)
.filter("difficulty", difficulty).order("score DESC").list();
现在我的问题如下:我如何确保这一点 1)调用addHighscore可以看到上次调用的结果 2)调用addHighscore然后getHighscore的客户端看到他的结果
我在https://developers.google.com/appengine/docs/java/datastore/structuring_for_strong_consistency阅读了解释,但我不知道如何将其应用到我自己的例子中。我可以用什么作为祖先钥匙?
有人可以解释我如何纠正这个问题吗? (如果可能的话,使用pseudycode样本)
更新
我改造了我的addHighscore函数,现在看起来像这个
boolean insert = ofy().transact(new Work<Boolean>() {
@Override
public Boolean run() {
// run sync
Key<Sync> ancestor = Sync.getKey();
if(ofy().load().key(ancestor).now() == null)
ofy().save().entities(new Sync()).now();
// check if free place in highscore
int count = ofy().load().type(Highscore.class).ancestor(ancestor).filter("difficulty", difficulty).order("-score").order("date").count();
boolean insert = count < MAX;
if(insert == false) {
// get last element and free if possible
Highscore least = ofy().load().type(Highscore.class).ancestor(ancestor).filter("difficulty", difficulty).order("-score").order("date").first().now(); // order DESC with -
if(highscore.getScore() > least.getScore()) {
ofy().delete().entity(least).now();
insert = true;
}
}
// insert
if(insert == true)
ofy().save().entity(highscore).now();
return insert;
}
});
同步
@Entity
public class Sync {
@Id long id = 1;
public static Key<Sync> getKey() {
return Key.create(Sync.class, 1);
}
}
此外,我通过@Parent Key<Sync> parent = Sync.getKey()
这似乎有效 - 我想知道这是否是一个合适的解决方案。或者有更好的方法吗?