All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.github.whimthen.kits.UniqueId Maven / Gradle / Ivy

There is a newer version: 1.0.4-RELEASE
Show newest version
package io.github.whimthen.kits;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 唯一id序列工具类
 * 		需要在config.properties中配置unique_seed_id为int类型的数值
 *
 * @project: kits
 * @created: with IDEA
 * @author: kits
 * @Date: 2018 09 26 2:47 PM | September. Wednesday
 */
public class UniqueId {

	private static final int SEQ_DEFAULT = 0;
	private static final int RADIX = 62;
	private static final int sequenceLeft = 12;
	private static final int signIdLeft = 10;
	private static final int maxsignId = 1 << signIdLeft;

	private static volatile AtomicInteger orderedIdSequence = new AtomicInteger(SEQ_DEFAULT);
	private static Long lastTime = 0L;
	private static int workId = 0;

	static {
		int signId = PropertiesKit.getInt("unique_seed_id");
		if(workId > maxsignId || signId < 0){
			throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxsignId));
		}
		workId = signId;
	}

	/**
	 * 获取下一个 IntId
	 * @return 返回 userId
	 */
	public static long nextInt(){
		return generateId();
	}

	/**
	 * 获取下一个 StringId
	 * @return 返回 userId
	 */
	public static String nextString(){
		return StringKit.radixConvert(generateId(), RADIX);
	}

	/**
	 * 生成带顺序的 ID 序列
	 * @return ID字符串
	 */
	public static synchronized long generateId(){
		long currentTime = System.currentTimeMillis();

		if(lastTime < currentTime){
			orderedIdSequence.set(SEQ_DEFAULT);
		}else if(lastTime > currentTime){
			throw new RuntimeException("Clock moved backwards.");
		}

		long resultId = (currentTime << (sequenceLeft+signIdLeft) ) | (workId << signIdLeft) | orderedIdSequence.getAndAdd(1);

		lastTime = currentTime;
		return resultId;
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy