使用Objectify同时在GAE上写入数据

时间:2013-06-05 05:26:31

标签: java google-app-engine google-cloud-datastore objectify

让我们举例说我有以下客观化模型:

@Cache
@Entity
public class CompanyViews implements Serializable, Persistence {

    @Id
    private Long id;
    private Date created;
    private Date modified;
    private Long companyId;

    ........

    private Integer counter;

    ........

    @Override
    public void persist() {
        persist(false);
    }

    @Override
    public void persist(Boolean async) {
        ObjectifyService.register(Feedback.class);
        // setup some variables
        setUuid(UUID.randomUUID().toString().toUpperCase());
        setModified(new Date());
        if (getCreated() == null) {
            setCreated(new Date());
        }   
        // do the persist
        if (async) {
            ofy().save().entity(this);
        } else {
            ofy().save().entity(this).now();
        }           
    }
}

我想使用计数器字段来跟踪视图的数量,或者打开数字或基本上使用整数字段计算某些内容。

现在发生的是,对于一个GAE实例,将调用以下内容:

答:

CompanyViews views = CompanyViews.findByCompanyId(...);
views.setCounter(views.getCounter() + 1);
views.persist();

和另一个例子:

B:

CompanyViews views = CompanyViews.findByCompanyId(...);
views.setCounter(views.getCounter() + 1);
views.persist();

如果他们同时读取计数器或在另一个实例持续存在之前读取计数器,它们将相互覆盖。

在MySQL / Postgres中,你获得了行级锁定,如何为GAE上的Objectify实体执行“行级锁定”?

1 个答案:

答案 0 :(得分:1)

在并发更新实体时,您需要使用transactions

请注意,由于您更新了同一个实体,因此您将有大约1个写入/秒的限制。要解决这个问题,请查看sharding counters