在Azure中DocumentDB文档中原子方式增加的一个整数 [英] Atomically increment an integer in a document in Azure DocumentDB

查看:234
本文介绍了在Azure中DocumentDB文档中原子方式增加的一个整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎么能原子方式增加在Azure中DocumentDB文档中的整数?

How can I atomically increment an integer in a document in Azure DocumentDB?

增量操作必须在并发作家presence原子。没有丢失增量允许的(他们将有可能在一个天真的读 - 修改 - 写算法)。

The increment operation must be atomic in the presence of concurrent writers. No lost increments are allowed (they would be possible in a naive read-modify-write algorithm).

推荐答案

从的文档

如何DocumentDB提供并发?

How does DocumentDB provide concurrency?

DocumentDB支持通过HTTP乐观并发控制(OCC)
  实体标签或ETag的。每个DocumentDB资源都有一个ETag和
  DocumentDB客户包括写他们最新的读版本
  要求。如果ETag的是最新的,提交了更改。如果
  值已从外部改变,服务器以拒绝写入
  HTTP 412 precondition失败响应code。客户必须读
  资源的最新版本,然后重试请求。

DocumentDB supports optimistic concurrency control (OCC) through HTTP entity tags or ETags. Every DocumentDB resource has an ETag, and DocumentDB clients include their latest read version in write requests. If the ETag is current, the change is committed. If the value has been changed externally, the server rejects the write with a "HTTP 412 Precondition failure" response code. Clients must read the latest version of the resource and retry the request.

我们可以使用这个属性来实现 CAS循环

One can use this property to implement a CAS loop:

 while (true) {
  var existingDoc = ReadDoc();

  existingDoc.Int++;

  try {
   WriteDoc(existingDoc);
   break;
  }
  catch { //Concurrency violation
   continue;
  }
 }

另外请注意,在天青DocumentDB交易的数据的快照(快照隔离)上运行

Also note that transactions in Azure DocumentDB run on a snapshot of the data (Snapshot Isolation).

BTW:如果你希望做一些更自动化(自动递增,当有人修改文档),您可以使用触发器和分离收集整的当前值。触发器在同一个事务中执行,因此将是一致的,自动化的。

BTW: If you would like to do something a bit more automated (auto increment when someone modifies a document) you can use a trigger and separated collection for current value of an integer. Triggers are executed in the same transaction so it would be consistent and automated.

这篇关于在Azure中DocumentDB文档中原子方式增加的一个整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆