创建 ObjectId vs 让数据库创建它

huangapple go评论69阅读模式
英文:

Creating ObjectId vs letting DB create it

问题

我正在使用labix mgo模块作为Go语言的Mongo驱动程序。由于Go是并发(和并行)的,所以在应用程序中生成ObjectId是否安全,还是应该只由数据库生成?

如果.Insert()能够返回Id,那就非常简单了。但是在我需要它的时候,有两种方法可以实现:

1)在客户端生成ObjectId并使用它

...
user.ID = bson.NewObjectId()
Users.Insert(user)
// 正常使用user.ID

2)让数据库生成Id并检索它

...
Users.Insert(user)
Users.Find(user).One(&user)
// 正常使用user.ID

第二种方法需要进行2次数据库请求和同步插入。

问题是:第一种方法和第二种方法一样安全吗?还是有更好的方法可以使用?

英文:

I am using labix mgo module as a Go Mongo driver. Since Go is concurrent (and parallel), is it safe to generate ObjectId in application or should only database do that?

It would be really straightforward if .Insert() could return Id. But this way when I need it, there are two approaches how I do that:

  1. generate ObjectId on client and use it

    ...
    user.ID = bson.NewObjectId()
    Users.Insert(user)
    // use user.ID normally

  2. let the database generate the Id and retrieve it

    ...
    Users.Insert(user)
    Users.Find(user).One(&user)
    // user user.ID normally

The second approach takes 2 database requests and the synchronous insert.

Question is: Is first approach safe as second is? Or is there something better I should be working with?

答案1

得分: 3

我会选择第一种方法,因为在这种情况下你不需要检索任何ID。

如果你查看ObjectID的描述,你会发现它由以下部分组成:

  • 一个4字节的值,表示自Unix纪元以来的秒数,
  • 一个3字节的机器标识符,
  • 一个2字节的进程ID,
  • 一个3字节的计数器,从一个随机值开始。

正如你所看到的,即使你使用同一台机器上的一个进程(使2和3相同),你仍然能够每秒插入3字节的整数。

所以如果你的写入速度小于(2^8)^3 - 1 = 16777215每秒,就不会发生冲突。

而每秒插入1600万条记录太不现实了。

英文:

I would go with the first approach, as you will not need to retrieve any ID in this case.

If you will look at the description of ObjectID, you will see that it consists of:

  • a 4-byte value representing the seconds since the Unix epoch,
  • a 3-byte machine identifier,
  • a 2-byte process id, and
  • a 3-byte counter, starting with a random value.

As you see, even if you use the same machine running on one process (making 2 and 3 the same), you still are able to insert 3 bytes integer per second.

So if your writing speed is less than (2^8)^3 - 1 = 16777215 per second, the collision will not happen.

And having 16 million inserts per second is too unrealistic.

huangapple
  • 本文由 发表于 2015年6月27日 03:03:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/31080415.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定