一.介绍
1.主键的组成: 系统当前时间取至毫秒(15位) + 机器IP(6位) + 原子性自增涨数字(3位) 共24位
2.支持每秒产生1000*1000个
3.扩展性:可以将自增涨数字位数扩大,这时每秒产生的主键也会自变多
二.代码
import com.common.exception.BizException;
import com.common.exception.ErrorCode;
import org.apache.commons.lang.StringUtils;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;
/**
* @describe: 主键工厂
* @author:houkai
*/
public class IdFactoryUtil {
private static HashMap<String, AtomicInteger> cache = new HashMap<String, AtomicInteger>(1);
private static final ReentrantLock lock = new ReentrantLock();
private static final SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmssSSS");
/**
* 获取主键
* @return
* @throws Exception
*/
public static String getId() {
String ip = null;
try {
ip = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
throw new BizException(ErrorCode.ID_FACTORY, e);
}
String[] ipArray = ip.split("\\.");
final String lastTwoPhaseIp = StringUtils.leftPad(ipArray[2], 3, '0') + StringUtils.leftPad(ipArray[3], 3, '0');
String tss = getTimeStampSequence();
String id = tss + lastTwoPhaseIp;
return id;
}
/**
* 获取指定数量的id
* @param amount : id数量
*/
public static List<String> getIds(final int amount){
String ip = null;
try {
ip = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
throw new BizException(ErrorCode.ID_FACTORY, e);
}
String[] ipArray = ip.split("\\.");
final String lastTwoPhaseIp = StringUtils.leftPad(ipArray[2], 3, '0') + StringUtils.leftPad(ipArray[3], 3, '0');
List<String> list = new ArrayList<>(amount);
for (int i = 0; i < amount; i++){
String tss = getTimeStampSequence();
String id = tss + lastTwoPhaseIp;
list.add(id);
}
return list;
}
private static String getTimeStampSequence() {
String timestamp = null;
String inc = null;
lock.lock();
try {
timestamp = sdf.format(new Date());
AtomicInteger value = cache.get(timestamp);
if(value == null) {
cache.clear();
int defaultStartValue = 0;
cache.put(timestamp, new AtomicInteger(defaultStartValue));
inc = String.valueOf(defaultStartValue);
} else {
inc = String.valueOf(value.addAndGet(1));
}
} finally {
lock.unlock();
}
return timestamp + StringUtils.leftPad(inc, 4, '0');
}
}
三. 代码需要的maven依赖
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>