How to generate unique id

試著忘記壹切 提交于 2021-02-05 08:25:10

问题


How can we generate unique id's between two JVMs running at the same time? I think UUID uuid = UUID.randomUUID(); or UID uid = new UID(); is not enough.


回答1:


You can concat to UUID server ID so UUID will be unique in all servers




回答2:


See UUID docs, you can follow the link to find the rfc4122 explaining how the UUID will be generated. The last 48 bits are concerning your question, the spacial unique node identifier confirming that this value will be a Universally Unique IDentifier.

4.1.2.  Layout and Byte Order

   To minimize confusion about bit assignments within octets, the UUID
   record definition is defined only in terms of fields that are
   integral numbers of octets.  The fields are presented with the most
   significant one first.

   Field                  Data Type     Octet  Note
                                        #

   time_low               unsigned 32   0-3    The low field of the
                          bit integer          timestamp

   time_mid               unsigned 16   4-5    The middle field of the
                          bit integer          timestamp

   time_hi_and_version    unsigned 16   6-7    The high field of the
                          bit integer          timestamp multiplexed
                                               with the version number


   clock_seq_hi_and_rese  unsigned 8    8      The high field of the
   rved                   bit integer          clock sequence
                                               multiplexed with the
                                               variant

   clock_seq_low          unsigned 8    9      The low field of the
                          bit integer          clock sequence

   node                   unsigned 48   10-15  The spatially unique
                          bit integer          node identifier

The only risk I can see come from that part

A UUID is an identifier that is unique across both space and time, with respect to the space of all UUIDs. Since a UUID is a fixed size and contains a time field, it is possible for values to rollover

But this would need to run for a long time before it come to you. So, I would not be worried to much with you current solution.



来源:https://stackoverflow.com/questions/44882649/how-to-generate-unique-id

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