英文:
couchbase golang json atomic increment
问题
在其他Couchbase SDK中是否有类似于counter的golang API,可以帮助我们原子地增加JSON文档中的某些字段?
例如,我有一个包含两个字段的结构体,它们将与文档D1关联:
type Counter struct {
c1 string `json:"c1"`
c2 string `json:"c2"`
}
对于每个HTTP请求,我想要原子地增加c1和c2。由于它们在JSON文档中,我无法使用GET方法,也不确定如何在golang中使用counter方法。
英文:
Is there a golang API similar to counter available in other couchbase SDK's that will help us to atomically increment certain fields inside a json document?
For example, I have a below struct with two fields which will be associated with a document D1
type Counter struct {
c1 string `json:"c1"`
c2 string `json:"c2"`
}
For every http request that comes in, I would like to do an atomic increment of c1 and c2. since it's within a json document, am not able to use GET and not sure how to use counter method using golang.
答案1
得分: 0
在文档中无法使用原子计数器,你有两个解决方法:
1)让你的文档引用单独的原子计数器,而不是保存计数器的值,它们只保存指向计数器的键。例如下面的 JSON,如果你检索到了文档,要使用计数器的值,你可以使用 'counter_key' 中的值。
{
"id": "customer::1343",
"name": "John Smith",
"counter_key": "counter::customer::1343"
}
2)第二个选项是在 JSON 文档中保留要递增的字段,为了能够原子地更新该字段,你需要使用 CAS(Compare and Swap)来进行乐观锁定,这将允许你在实际文档中更新该值,而不是使用单独的计数器。这种方法会引入额外的编码开销,并且性能不如单独的计数器。你可以在这里了解更多关于 CAS 的信息:http://docs.couchbase.com/developer/dev-guide-3.0/retrieve-by-cas.html
在 Stack Overflow 上也有一个关于 Couchbase CAS 的简洁描述:https://stackoverflow.com/questions/22601503/what-is-cas-and-how-to-use-it
英文:
It's not possible to have an atomic counter within a document, you have two options to work around this:
-
Have your document reference separate atomic counters, rather than holding the counter value they'll just hold the key that points to the counter. Something like the json below, if you retrieved the document then to work with the counter you'd use the value in 'counter_key'.
{
"id": "customer::1343"
"name": "John Smith",
"counter_key": "counter::customer::1343"
} -
Your second option is to keep the field within the Json document that you want to increment, to be able to update this atomically you'll need to look at CAS which is a form of optimistic locking which will allow you to update the value within the actual document rather than having a separate counter, this method does introduce additional coding overhead and won't be as performant as a separate counter. You can read about more about CAS here: http://docs.couchbase.com/developer/dev-guide-3.0/retrieve-by-cas.html
There is also a nice succinct description here of Couchbase CAS here on Stack Overflow: https://stackoverflow.com/questions/22601503/what-is-cas-and-how-to-use-it
专注分享java语言的经验与见解,让所有开发者获益!
评论