• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

JAVA ID生成器生成逻辑主键_java

java 搞代码 7年前 (2018-08-06) 292次浏览 已收录 0个评论

在一个数据库设计里,假如使用了逻辑主键,那么你一般都需要一个ID生成器去生成逻辑主键。 

在许多数据库里面,都提供了ID生成的机制,如oracle中的sequence,MSSQL中的identity,可惜这些方法各种数据库都不同的,所以很多人愿意找寻一种通用的方式。 

编写代码,1、2、3……这样一直累加是最直接的想法,java用以下方式去实现 

private static AtomicInteger uniqueId = new AtomicInteger(0);

public static String nextId() {

http://www.gaodaima.com/64997.htmlJAVA ID生成器生成逻辑主键_java

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原版本的实现了。 
 

欢迎大家阅读《JAVA ID生成器生成逻辑主键_java》,跪求各位点评,若觉得好的话请收藏本文,by 搞代码


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:JAVA ID生成器生成逻辑主键_java

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址