自动ID的生成
1.多机集群的环境下生成的ID
@Override
public long getIdentityid ( ) {
long currentTime = System. currentTimeMillis ( ) ;
while ( ! identityidValid. valid ( currentTime) ) {
try {
Thread. sleep ( Constants. ONE) ;
} catch ( InterruptedException e) {
logger. error ( "Thread sleep error!" , e) ;
}
currentTime = System. currentTimeMillis ( ) ;
}
int incNumber = atomicInc. getAndIncrement ( ) ;
return ( currentTime - BENCHMARK_TIME) << Constants. TWENTY | ( machineId << 15 ) | ( incNumber & INCNUMBER_AND_NUMBER) ;
其中identityidValid是检测ID是否重复
private class IdentityidValid {
public long time;
public int count;
IdentityidValid ( long time, int count) {
this . time = time;
this . count = count;
}
public boolean valid ( long time) {
if ( time != this . time) {
this . time = time;
this . count = 0 ;
return true ;
}
if ( this . count < INCNUMBER_AND_NUMBER) {
this . count++ ;
return true ;
}
return false ;
}
}
2.单机的生成方法
@Override
public long getIdentityid ( ) {
long identityid = ( System. currentTimeMillis ( ) - BENCHMARK_TIME) << Constants. TWENTY;
int incNumber = atomicInc. getAndIncrement ( ) ;
return identityid | ( incNumber & INCNUMBER_AND_NUMBER) ;
}