I wanted to know if Couchbase support consistent incremental Counters. From what I've read in this doc, it does not, it just encapsulates a read/write operation so you won't need to do it yourself. Of course this doesn't work for me because the data might change since the time you read the data from the database.
问题:
回答1:
Couchbase absolutely does, just like memcached and Membase Server, it supports the incr/decr operations atomically within a cluster.
cb.set("mykey", 1)
x = cb.incr("mykey")
puts x #=> 2
incr is both writing and returning the resulting value.
"The update operation occurs on the server and is provided at the protocol level." means that it is atomic on the cluster, and executed by the server.
"This simplifies what would otherwise be a two-stage get and set operation." means that instead of a two-stage operation, it is a single operation!
回答2:
If you are using the Java API, since the release of version 2.0, the incr methods has been replaced by the counter method.
You would need to use the counter method of your bucket. This method allows you to define the name of the counter document (which holds a long type) and the increment. If the doc does not exists, it creates it. Many other parameters are defined in the official documentation.
//Obtain the id from counter document and increment it
com.couchbase.client.java.Bucket bucket;
JsonLongDocument joCounter = bucket.counter("counter", 1);
//get the counter long value (might be useful to generate doc id)
long newCounter = joCounter.content();
This operation is atomic, so feel safe to use counters. http://docs.couchbase.com/developer/java-2.0/documents-atomic.html