admin 管理员组

文章数量: 887007

Java.Utils:生成不重复的编号

Don’t say much, just go to the code.

package org.boodmon.utils;import org.apachemons.lang3.time.FastDateFormat;import java.time.Instant;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicInteger;/*** 生成不重复的编号** @author bood* @since 2020/9/25*/
public class ODDGenerator {private static final FastDateFormat PATTERN = FastDateFormat.getInstance("yyyyMMddHHmmss");private static final AtomicInteger ATOMICINTEGER = new AtomicInteger(1);private static ThreadLocal<StringBuilder> THREADLOCAL = new ThreadLocal<>();private ODDGenerator() {}/*** <p>* 【长码生成策略】* </p>** @param lock: 随机字符串* @return:java.lang.String* @author:bood* @date:2020/9/25*/public static String getC(String lock) {try {// 取系统当前时间作为编号前半部分StringBuilder builder = new StringBuilder(PATTERN.format(Instant.now().toEpochMilli()));// HASH-CODEbuilder.append(Math.abs(lock.hashCode()));// 自增顺序builder.append(ATOMICINTEGER.getAndIncrement());THREADLOCAL.set(builder);return String.valueOf(THREADLOCAL.get());} finally {THREADLOCAL.remove();}}/*** <p>* 【短码生成策略】* </p>** @param lock: 随机字符串* @return:java.lang.String* @author:bood* @date:2020/9/25*/public static String getD(String lock) {try {// 随机数StringBuilder builder = new StringBuilder(ThreadLocalRandom.current().nextInt(0, 999));// HASH-CODEbuilder.append(Math.abs(lock.hashCode()));// 自增顺序builder.append(ATOMICINTEGER.getAndIncrement());THREADLOCAL.set(builder);return String.valueOf(THREADLOCAL.get());} finally {THREADLOCAL.remove();}}}

本文标签: JavaUtils生成不重复的编号