Java 生成隨機單據(jù)號的實現(xiàn)示例
背景:全局生成4位字符2222-9ZZ9
實現(xiàn)方式:
使用redis的原子自增 + google的retry保證,生成4位數(shù)
1、pom
<dependency>
<groupId>com.github.rholder</groupId>
<artifactId>guava-retrying</artifactId>
<version>2.0.0</version>
</dependency>2、獲取單號序列重試器
private final Retryer<Long> getOrderSequenceRetryer = RetryerBuilder.<Long>newBuilder()
.retryIfResult(Objects::isNull).retryIfException()
.withWaitStrategy(WaitStrategies.incrementingWait(30, TimeUnit.MILLISECONDS, 10, TimeUnit.MILLISECONDS))
.withStopStrategy(StopStrategies.stopAfterAttempt(2)).build();3、redis原子自增 + guava的重試機制保證
private String getFallbackSuffix() {
Long num;
try {
num = getOrderSequenceRetryer.call(
() -> redisGateway.incr()//使用redis的原子自增+1,并設置過期時間
);
} catch (Exception e) {
throw new RuntimeException("redis incr exception", e);
}
return getSuffix(num.intValue());
}4、將生成的原子自增數(shù),取后綴,最終4位范圍【2222-9ZZ9】和業(yè)務相關
/**
* 獲取后綴
* [(2-9), (2-9,A-H,J-N,P-Z), 2-9,A-H,J-N,P-Z), (2-9)]
* 2222-9ZZ9
*
* @param num num
* @return suffix
*/
public static String getSuffix(int num) {
String[] suffixFactors = new String[]{"2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F",
"G", "H", "J", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
// 65536 = 8 * 32 * 32 * 8
int serialNumberThreshold = 65536;
if (num >= 0 && num < serialNumberThreshold) {
int index4 = num / 8192;
int mod4 = num % 8192;
int index3 = mod4 / 256;
int mod3 = mod4 % 256;
int index2 = mod3 / 8;
int mod2 = mod3 % 8;
return suffixFactors[index4] + suffixFactors[index3] + suffixFactors[index2] + suffixFactors[mod2];
}
throw new IllegalArgumentException("num 超過流水號閾值,單號可能會重復!!!");
}注意事項
1、單據(jù)號中,最好不要說使用1和l,0和o(數(shù)字只能用8個,字母只能用大寫的24個)
2、guava的重試機制參考:http://www.dbjr.com.cn/program/299337r11.htm
UUID
public class IdUtil {
/*
* 返回使用ThreadLocalRandom的UUID,比默認的UUID性能更優(yōu)
*/
public static UUID fastUUID() {
ThreadLocalRandom random = ThreadLocalRandom.current();
return new UUID(random.nextLong(), random.nextLong());
}
}隨機生成前綴 + 日期 + 后綴隨機5位數(shù)
private static final DateTimeFormatter FORMATTER_DATE_YYYYMMDDHHMMSS = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
@Test
public void t() throws Exception {
String suffix = StringUtils.leftPad(String.valueOf(new Random().nextInt(100)), 5, "0");
String result = "prefix" + formatLocalDateTime(LocalDateTime.now()) + suffix;
}
public static String formatLocalDateTime(LocalDateTime localDateTime) {
return FORMATTER_DATE_YYYYMMDDHHMMSS.format(localDateTime);
}到此這篇關于Java 生成隨機單據(jù)號的實現(xiàn)示例的文章就介紹到這了,更多相關Java 生成隨機單據(jù)號內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
SpringBoot Data JPA 關聯(lián)表查詢的方法
這篇文章主要介紹了SpringBoot Data JPA 關聯(lián)表查詢的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-07-07
Java MultipartFile實現(xiàn)上傳文件/上傳圖片
這篇文章主要介紹了Java MultipartFile實現(xiàn)上傳文件/上傳圖片,幫助大家更好的理解和使用Java,感興趣的朋友可以了解下2020-12-12

