package fanan;
import java.net.InetAddress;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;
/**
* ID生成规则 日期(两位) + 机器IP(后三位) + 当前毫秒数去掉前两位(11位)+ 6位自增的Long类型
*
* @author 高江涛
* @date Oct 29, 2013
*/
public class IdCreator {
private static Random random = new Random();
//AtomicLong 的活动范围
private static final int MIN_VALUE = 10000;
private static final int MAX_VALUE = 99999;
private static AtomicLong atomiclong = new AtomicLong(MIN_VALUE);
public long getTaskId(Date date) {
StringBuilder sb = new StringBuilder();
sb.append(getAtomicLongValue());
//sb.append( sdf.format(date));
sb.append(getHostIpLast3());
sb.append(getTimeMillis());
return Long.parseLong(sb.toString());
}
/**
* 获取服务器Ip的最后一段 如192.168.1.20 返回 20
*
* @return Ip尾段
*/
public String getHostIpLast3() {
String hostIp = "000";
try {
hostIp = InetAddress.getLocalHost().getHostAddress();
String[] ips = hostIp.split("\\.");
hostIp = ips[ips.length - 1];
if (hostIp.length() == 2) {
hostIp = "0" + hostIp;
}
} catch (Exception e) {
hostIp = random.nextInt(1000) + "";
}
return hostIp;
}
/**
* 获取到毫秒数 去掉前两位
* @return
*/
public String getTimeMillis() {
String times = System.currentTimeMillis() + "";
times = times.substring(2, times.length());
return times;
}
/**
* 获取当前的 Long值 重复循环
* @return
*/
public String getAtomicLongValue(){
synchronized (atomiclong) {
atomiclong.compareAndSet(MAX_VALUE, MIN_VALUE);
return atomiclong.addAndGet(1)+"";
}
}
public static void main(String[] args) {
IdCreator mcId = new IdCreator();
for (int i = 0; i < 10000; i++) {
System.out.println(mcId.getTaskId(new Date()));
};
}
}