Java to generate a single sequence number of the implementation of the method

  • 2020-04-01 02:41:56
  • OfStack


import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.lang3.StringUtils;

public class SerialNum {
 private static String count = "000";
 private static String dateValue = "20131115";
 
 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;
 }
 
 public synchronized static String getMoveOrderNo(String serialNum) {
  String nyr = StringUtils.substring(serialNum, 2, 10); //Gets 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();
 }
 
 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 procedure if the server has been able to run normally would not have what problem, if you restart the server or there is any fault need to restart the service may cause duplicate serial number, in order to ensure that only, we need to cooperate on database query, query and finally a record, then take out the serial number on the call getMoveOrderNo (String serialNum) this method, can guarantee what case generated serial number is the only right.


Related articles: