业务订单号生成算法,每秒50W左右,不同机器保证不重复,包含日期可读性好
FilUtils不想用的话,1太机器可以直接考虑使用1,多机器根据代码配置id
代码如下:
OrderNoCenter { Logger logger = LoggerFactory.getLogger(OrderNoCenter.class); String WORKERID_PATH = "/etc/workerId"; private OrderNoCenter() { } OrderNoCenterHolder{ (); } public static OrderNoCenter getInstance() { return OrderNoCenterHolder.instance; } workerId = 1; sequence = 1; workerIdBits = 10L; maxWorkerId = -1L ^ (-1L << workerIdBits); sequenceBits = 12L; workerIdShift = sequenceBits; datacenterIdShift = sequenceBits + workerIdBits; sequenceMask = -1L ^ (-1L << sequenceBits); timestampLeftShift = sequenceBits + workerIdBits; private long lastTimestamp = -1L; () { // 从默认位置读取workerId,最大1024 try { File conf = new File(WORKERID_PATH); if(conf.exists()){ String str = FileUtils.readFileToString(conf); workerId = Integer.parseInt(str); }else{ logger.warn(" worker id not found,will use default value..."); } } catch(Exception e){ e.printStackTrace(); } logger.info(" worker id is {}",workerId); if (workerId < 0 || workerId > maxWorkerId) { throw new IllegalArgumentException("workerId is illegal: " + workerId); } } () { return workerId; } () { return System.currentTimeMillis(); } public String create() { return nextNo(); } String nextNo() { long timestamp = timeGen(); // 时间错误 if (timestamp < lastTimestamp) { throw new IllegalStateException("Clock moved backwards."); } // 当前毫秒内,则+1 if (lastTimestamp == timestamp) { // 当前毫秒内计数满了,则等待下一秒 sequence = (sequence + 1) & sequenceMask; if (sequence == 0) { timestamp = tilNextMillis(lastTimestamp); } } else { sequence = 0; } lastTimestamp = timestamp; // ID偏移组合生成最终的ID,并返回ID,最大十位数 long id = ((timestamp % 1000) << timestampLeftShift) | (workerId << workerIdShift) | sequence; String timestampStr = DateFormatUtils.NUMBER_FORMAT.format(timestamp); ,id); } (long lastTimestamp) { long timestamp = timeGen(); while (timestamp <= lastTimestamp) { timestamp = timeGen(); } return timestamp; } () { return System.currentTimeMillis(); } (String[] args){ for (int i = 0; i < 100; i++) { System.out.println(OrderNoCenter.getInstance().create()); } //性能测试 TimeMark mark = new TimeMark(); for (int i = 0; i < 1000000; i++) { OrderNoCenter.getInstance().create(); } mark.simplePrint(); mark.mark(); for (int i = 0; i < 1000000; i++) { IdCenter.getInstance().getId(); } mark.simplePrint(); } }
缺少代码的话,请直接使用我的附件代码
附件:
代码代码代码代码代码点击下载下载
posted @