gonet icon indicating copy to clipboard operation
gonet copied to clipboard

NextVal并发问题

Open NicholeGit opened this issue 11 years ago • 5 comments

func NextVal(countername string) int32 会有bug,当开始同时有两个请求到达时就会插入两条记录 可以是用_id为countername这样可以避免

NicholeGit avatar Feb 12 '15 06:02 NicholeGit

update操作应该是原子的

xtaci avatar Feb 12 '15 09:02 xtaci

你看看 http://docs.mongodb.org/manual/tutorial/create-an-auto-incrementing-field/ findAndModify Behavior 里面有讲解 你这个gonet还会继续更新吗?

NicholeGit avatar Feb 13 '15 03:02 NicholeGit

When findAndModify() includes the upsert: true option and the query field(s) is not uniquely indexed, the method could insert a document multiple times in certain circumstances.

是的,两个条件同时满足的时候才会发生。

  1. upsert == true
  2. 没有建立unique索引

这个确实需要特别注意。

这个库会持续更新,如果有更好的实践经验,我会归纳到这里。

xtaci avatar Feb 15 '15 02:02 xtaci

出现这种的可能性,是记录不存在的时候,有同时进行的upsert,就可能会创建多条记录。但只要已经存在这条记录的时候,是不应该创建出来的。

不过简单起见, 分为两步走更合适:

  1. 预先创建记录
  2. 直接$inc操作。

xtaci avatar Feb 15 '15 02:02 xtaci

能不能提供一个测试客户端啊

0x5143 avatar Apr 13 '15 02:04 0x5143