且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我可以从Azure Cosmos DB中读取/加载文档并同时获得对其的写入锁定吗?

更新时间:2023-02-14 11:57:53

AFAIK,至少在撰写此答案时,Cosmos DB不支持您要查找的内容(获取写锁定).今天支持的是 Optimistic Concurrency using ETags 适用于顺序写入,但不是您要找的.​​ p>

只需大声思考,您就可以使用 Blob存储中提供了Lease 功能,并将其与Cosmos DB写入操作结合使用.

基本上,将要发生的是,您的工作进程将尝试在一定时间内(15-60秒)在Blob上获取租约.只有一名工人能够获得租约.该工作人员将有机会在获得锁的时间内更新Cosmos DB中的文档.另一个工作进程将不得不等待,直到租约到期或第一个工作进程显式破坏了租约.

这与此处描述的Leader Election Pattern有点相似: https://docs.microsoft.com/zh-CN/azure/architecture/patterns/leader-election .

Basically I want to know that only one party is going to change the document. I want to avoid situation when 2 different instances of a worker role or different worker roles will read the same state of the document and then each will write its own modification, potentially different. Sequential writes may easily go fine one after another, but this is not what I want.

This writing lock should auto expire after some time if write will not happen for whatever reason.

I heard some rumors that this is possible, but I cannot find this in the documentation.

AFAIK, what you're looking for (acquiring write lock) is not supported by Cosmos DB at least as of writing of this answer. What's supported today is Optimistic Concurrency using ETags that is suitable for sequential writes but that's not you're looking for.

Just thinking out loud, you can however make use of Lease functionality available in blob storage and use that in conjunction with your Cosmos DB write operation.

Essentially what will happen is your worker processes will try to acquire a lease on a blob for certain duration (15-60 seconds). Only one worker will be able to acquire a lease. That worker will have an opportunity to update the document in Cosmos DB for the duration it has acquired the lock. The other worker process will have to wait till the lease has been expired or the 1st worker has explicitly broken the lease.

This is somewhat similar to Leader Election Pattern described here: https://docs.microsoft.com/en-us/azure/architecture/patterns/leader-election.