Copy the code code as follows:
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.lang3.StringUtils;
/**
* Generate serial number tool class
* @version V1.0
* @date: 2013-11-16 5:21:37 pm
*/
public class SerialNum {
private static String count = "000";
private static String dateValue = "20131115";
/**
* Generate serial number
*/
public synchronized static String getMoveOrderNo() {
long No = 0;
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String nowdate = sdf.format(new Date());
No = Long.parseLong(nowdate);
if (!(String.valueOf(No)).equals(dateValue)) {
count = "000";
dateValue = String.valueOf(No);
}
String num = String.valueOf(No);
num += getNo(count);
num = "CB" + num;
return num;
}
/**
* Obtain the serial number of the move-out order
*/
public synchronized static String getMoveOrderNo(String serialNum) {
String nyr = StringUtils.substring(serialNum, 2, 10); // Get the year, month and day string
String countV = StringUtils.substring(serialNum, 10); // Get the serial number
if (Integer.valueOf(countV) > Integer.valueOf(count)) {
dateValue = nyr;
count = String.valueOf(countV);
}
return getMoveOrderNo();
}
/**
* Returns the number of orders for the day +1
*/
public static String getNo(String s) {
String rs = s;
int i = Integer.parseInt(rs);
i += 1;
rs = "" + i;
for (int j = rs.length(); j < 3; j++) {
rs = "0" + rs;
}
count = rs;
return rs;
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
System.out.println(getMoveOrderNo());
}
}
}
Note: The above program will not cause any problems if the server can always run normally. If the server is restarted or there is any failure in the process and the service needs to be restarted, it may cause duplicate serial numbers to be generated. In order to ensure uniqueness, we need to cooperate with the database query. , query the last record, and then take out the serial number and call the getMoveOrderNo(String serialNum) method to ensure that the generated serial number is correct and unique under any circumstances.