What is CAS in NoSQL and how to use it?

末鹿安然 提交于 2019-12-03 01:41:35

CAS actually stands for check-and-set, and is a method of optimistic locking. The CAS value is associated with each document which is updated whenever the document changes - a bit like a revision ID. The intent is that instead of pessimistically locking a document (and the associated lock overhead) you just read it's CAS value, and then only perform the write if the CAS matches.

The general use-case is:

  1. Read an existing document, and obtain it's current CAS (get_with_cas)
  2. Prepare a new value for that document, assuming no-one else has modified the document (and hence caused the CAS to change).
  3. Write the document using the check_and_set operation, providing the CAS value from (1).

Step 3 will only succeed (perform the write) if the document is unchanged between (1) and (3) - i.e. no other user has modified it in the meantime. Typically if (3) does fail you would retry the whole sequence (get_with_cas, modify, check_and_set).

There's a much more detailed description of check-and-set in the Couchbase Developer Guide under Concurrent Document Mutations.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!