国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

教你用JAVA ID生成器去生成邏輯主鍵

2019-11-18 12:37:15
字體:
來源:轉載
供稿:網友

  在一個數據庫設計里,假如使用了邏輯主鍵,那么你一般都需要一個ID生成器去生成邏輯主鍵。
  
  在許多數據庫里面,都提供了ID生成的機制,如Oracle中的sequence,MSSQL中的identity,可惜這些方法各種數據庫都不同的,所以很多人愿意找尋一種通用的方式。
  
  編寫代碼,1、2、3……這樣一直累加是最直接的想法,java用以下方式去實現
  
  PRivate static AtomicInteger uniqueId = new AtomicInteger(0);
  
  public static String nextId() {
  return Integer.toString(uniqueId.incrementAndGet());
  }
  
  當然,這樣太簡單了,并且一重新啟動,計數器就歸 0 了,一般的做法可以用 時間 + 計數器 的方式,
  
  private static final long ONE_STEP = 10;
  private static final long BASE = 1129703383453l;
  
  private static final Lock LOCK = new ReentrantLock();
  
  private static long lastTime = System.currentTimeMillis();
  private static short lastCount = 0;
  
  /**
  * a time (as returned by {@link System#currentTimeMillis()}) at which
  * the VM that this UID was generated in was alive
  * @serial
  */
  private final long time;
  
  /**
  * 16-bit number to distinguish UID instances created
  * in the same VM with the same time value
  * @serial
  */
  private final short count;
  
  /**
  * Generates a UID that is unique over time with
  * respect to the host that it was generated on.
  */
  public UID() {
  LOCK.lock();
  try {
  if (lastCount == ONE_STEP) {
  boolean done = false;
  while (!done) {
  long now = System.currentTimeMillis();
  if (now == lastTime) {
  // pause for a second to wait for time to change
  try {
  Thread.currentThread().sleep(1);
  }
  catch (java.lang.InterruptedException e) {
  } // ignore exception
  continue;
  }
  else {
  lastTime = now;
  lastCount = 0;
  done = true;
  }
  }
  }
  time = lastTime;
  count = lastCount++;
  }
  finally {
  LOCK.unlock();
  }
  }
  在一個群集的環境里面,通常還需要加上ip的前綴,即 IP + 時間 + 計數器,這個就是JAVA原版本的實現了。
  
  但是,覺得這個ID太長了?那沒辦法,回到用數據庫的方法吧。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 建宁县| 岢岚县| 临湘市| 阿拉善左旗| 汝南县| 瑞安市| 龙门县| 日照市| 平果县| 乐至县| 神木县| 宜黄县| 临安市| 金山区| 庆阳市| 搜索| 曲沃县| 黑山县| 兰州市| 江孜县| 南江县| 青铜峡市| 定安县| 彭阳县| 许昌县| 嘉义市| 句容市| 九龙县| 梅州市| 阳原县| 崇阳县| 玛纳斯县| 麻栗坡县| 临沧市| 定南县| 开江县| 泸溪县| 陇西县| 临高县| 黎川县| 扎兰屯市|