简体   繁体   English

如何通过部署在没有数据库的多个服务器上的服务为每个呼叫生成一个 16 位唯一号码?

[英]How to generate a 16 digit unique number for each call by a service deployed on multiple servers without database?

I have a Java service that generates a 16 digit unique number using current time in the format yymmddhhmmssmsms.我有一个 Java 服务,它使用当前时间以 yymmddhhmmssmsms 格式生成一个 16 位唯一数字。 And it handles multiple calls on the same mili-second using Atomic Long.它使用 Atomic Long 在同一毫秒内处理多个调用。 But now the problem is that I need this service on multiple cloud machines.但是现在的问题是我需要在多台云机器上使用这个服务。 How can I handle calls at the same microsecond on different servers and generate a unique number for each of this calls.如何在不同的服务器上以相同的微秒处理呼叫并为每个呼叫生成一个唯一的号码。 And I dont want to use database for this.我不想为此使用数据库。

EDIT: I understand UUID can be a solution.编辑:我知道 UUID 可以是一个解决方案。 But UUID generates a random no.但是 UUID 会生成一个随机编号。 everytime, not unique, though the chances of collision are very low.每次都不是唯一的,尽管碰撞的机会非常低。

A think, you can try to use UUID.randomUUID() object一想,可以尝试使用 UUID.randomUUID() object

The UUID v4 is the right choice for distributed systems. UUID v4 是分布式系统的正确选择。

The UUID v4 implementation uses random numbers as the source. UUID v4 实现使用随机数作为源。 The Java implementation is SecureRandom – which uses an unpredictable value as the seed to generate random numbers to reduce the chance of collisions. Java 实现是 SecureRandom - 它使用不可预测的值作为种子来生成随机数以减少冲突的机会。 Source: https://www.baeldung.com/java-uuid来源: https://www.baeldung.com/java-uuid

Secure Random: This class provides a cryptographically strong random number generator (RNG).安全随机:此 class 提供加密强随机数生成器 (RNG)。 Source: https://docs.oracle.com/javase/8/docs/api/java/security/SecureRandom.html资料来源: https://docs.oracle.com/javase/8/docs/api/java/security/SecureRandom.html

Example how to use the UUID:如何使用 UUID 的示例:

UUID uuid = UUID.randomUUID();

Using a random number alone (such as a random UUID) should only be done if—仅在以下情况下才应仅使用随机数(例如随机 UUID):

  • you have a way to check the number for uniqueness across all calls, or您有办法在所有呼叫中检查号码的唯一性,或者
  • you can tolerate the risk of generating the same number for different calls.您可以容忍为不同的呼叫生成相同号码的风险。

If you find it appropriate, try assigning each server a unique number (eg, by requesting a unique number from a central database).如果您认为合适,请尝试为每个服务器分配一个唯一编号(例如,通过从中央数据库请求一个唯一编号)。 Then each server can generate a unique ID for each call it makes by appending a random number to that unique number;然后,每个服务器可以通过在该唯一编号上附加一个随机数来为其发出的每个调用生成一个唯一 ID; this may work well because the server can now more easily check the IDs it then generates for uniqueness, as no further contact with a central database or other servers is required.这可能会很好,因为服务器现在可以更轻松地检查它生成的 ID 的唯一性,因为不需要进一步联系中央数据库或其他服务器。

See also my section on generating unique random identifiers .另请参阅我关于生成唯一随机标识符的部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM