Java 如何根据当前日期生成 UniqueId
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26400779/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to generate a UniqueId based on current date
提问by
I am generating a OrderId which should consist of yyMMddhhmmssMs and this orderId represents primarykey field for the Orders table .
我正在生成一个 OrderId,它应该由 yyMMddhhmmssMs 组成,这个 orderId 代表 Orders 表的主键字段。
The way i was generating Order Id is below :
我生成订单 ID 的方式如下:
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateTime {
public static String getCurrentDateTimeMS() {
Date dNow = new Date();
SimpleDateFormat ft = new SimpleDateFormat("yyMMddhhmmssMs");
String datetime = ft.format(dNow);
return datetime;
}
public static void main(String args[]) throws InterruptedException {
for (int i = 0; i < 50; i++) {
String orderid = DateTime.getCurrentDateTimeMS();
System.out.println(orderid);
}
}
}
But when i load tested my Application using JMeter with 100 users with a ramp up of 2 seconds most of them were throwing Duplicate as shown below
但是,当我使用 JMeter 对我的应用程序进行负载测试时,有 100 名用户以 2 秒的速度上升,其中大多数人都在抛出重复,如下所示
java.sql.BatchUpdateException: Duplicate entry '1410160239241024' for key 'PRIMARY'
at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:1269)
at com.mysql.jdbc.PreparedStatement.executeBatch(PreparedStatement.java:955)
at com.services.OrdersInsertService.getData(OrdersInsertService.java:86)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
How is it possible to generating UniqueId based on current time so that it never fails no matter how many concurrent users are present .
如何根据当前时间生成 UniqueId 以便无论存在多少并发用户都不会失败。
回答by
Add a unique string to each order ID, like the user's email (if it's unique in your database) or the user's id from your database. This makes the order ID truly unique
为每个订单 ID 添加一个唯一的字符串,例如用户的电子邮件(如果它在您的数据库中是唯一的)或您数据库中的用户 ID。这使得订单 ID 真正独一无二
String unique = timestamp + unique_user_field
字符串唯一 = 时间戳 + unique_user_field
回答by CoderCroc
This is happening because of speed of for
loop which is faster than your time:).As loop iterates in time of less than miliseconds and generates values.You can only call it when you want to insert single value to database and don't iterate for values.
发生这种情况是因为for
循环速度比您的时间快:)。因为循环在不到几毫秒的时间内迭代并生成值。您只能在想要将单个值插入数据库时调用它并且不迭代值。
Other than that you can use UUID
for this purpose (for alphanumeric value).
除此之外,您可以UUID
用于此目的(用于字母数字值)。
for (int i = 0; i < 50; i++) {
Date dNow = new Date();
SimpleDateFormat ft = new SimpleDateFormat("yyMMddhhmmssMs");
String datetime = ft.format(dNow);
System.out.println(datetime);
}
OUTPUT
输出
141016030003103
141016030003103
141016030003103
141016030003103
141016030003103
141016030003103
141016030003103
141016030003103
141016030003103
//.....and more
回答by Keshav Sharma
public class Test {
公共类测试{
public static void main(String[] args) {
Date d=new Date();
//it will return unique value based on time
System.out.println(d.getTime());
}
}
you can use getTime method of date class. it returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this date.
您可以使用日期类的 getTime 方法。它返回自 1970 年 1 月 1 日格林威治标准时间 00:00:00 以来由该日期表示的毫秒数。
回答by HIREN011
This code will help you generate any number of unique IDs using current time stamp. Generated ID is of type long - 64 bits. Least Significant 17 bits are used when request to generate a new unique ID is received in the same millisecond of time as the previous request. Its identified as Sequence in the code below. That allows the code to generate 65536 unique IDs per millisecond.
此代码将帮助您使用当前时间戳生成任意数量的唯一 ID。生成的 ID 是 long 类型的 - 64 位。当在与前一个请求相同的毫秒时间内接收到生成新唯一 ID 的请求时,使用最低有效 17 位。它在下面的代码中标识为 Sequence 。这允许代码每毫秒生成 65536 个唯一 ID。
/**
* Unique id is composed of:
* current time stamp - 47 bits (millisecond precision w/a custom epoch gives as 69 years)
* sequence number - 17 bits - rolls over every 65536 with protection to avoid rollover in the same ms
**/
public class UniqueIdGenerator {
private static final long twepoch = 1288834974657L;
private static final long sequenceBits = 17;
private static final long sequenceMax = 65536;
private static volatile long lastTimestamp = -1L;
private static volatile long sequence = 0L;
public static void main(String[] args) {
Set<Long> uniqueIds = new HashSet<Long>();
long now = System.currentTimeMillis();
for(int i=0; i < 100000; i++)
{
uniqueIds.add(generateLongId());
}
System.out.println("Number of Unique IDs generated: " + uniqueIds.size() + " in " + (System.currentTimeMillis() - now) + " milliseconds");
}
private static synchronized Long generateLongId() {
long timestamp = System.currentTimeMillis();
if (lastTimestamp == timestamp) {
sequence = (sequence + 1) % sequenceMax;
if (sequence == 0) {
timestamp = tilNextMillis(lastTimestamp);
}
} else {
sequence = 0;
}
lastTimestamp = timestamp;
Long id = ((timestamp - twepoch) << sequenceBits) | sequence;
return id;
}
private static long tilNextMillis(long lastTimestamp) {
long timestamp = System.currentTimeMillis();
while (timestamp <= lastTimestamp) {
timestamp = System.currentTimeMillis();
}
return timestamp;
}
}
回答by Prashanth
Use this:
用这个:
int unique_id= (int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE);
回答by Neyomal
I used a simple logical approach which combines current date and time. That way it is absolutely unique in any given time.
public String setUniqueID(){
DateFormat dateFormat = new SimpleDateFormat("yyddmm");
Date date = new Date();
String dt=String.valueOf(dateFormat.format(date));
Calendar cal = Calendar.getInstance();
SimpleDateFormat time = new SimpleDateFormat("HHmm");
String tm= String.valueOf(time.format(new Date()));//time in 24 hour format
String id= dt+tm;
System.out.println(id);
return id;
}
This returns a unique id.
回答by Anees Hameed
You can use new Date().getTime().toString(36);
which gives a string something like 'u2mcggc1'
您可以使用new Date().getTime().toString(36);
which 给出一个类似于 'u2mcggc1' 的字符串