服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

教你用java id生成器去生成逻辑主键


  在一个数据库设计里,假如使用了逻辑主键,那么你一般都需要一个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太长了?那没办法,回到用数据库的方法吧。

扫描关注微信公众号