Java 生成随机单据号的实现示例
作者:tmax52HZ
本文主要介绍了Java 生成随机单据号的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
背景:全局生成4位字符2222-9ZZ9
实现方式:
使用redis的原子自增 + google的retry保证,生成4位数
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、将生成的原子自增数,取后缀,最终4位范围【2222-9ZZ9】和业务相关
/** * 获取后缀 * [(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、单据号中,最好不要说使用1和l,0和o(数字只能用8个,字母只能用大写的24个)
2、guava的重试机制参考:https://www.jb51.net/program/299337r11.htm
UUID
public class IdUtil { /* * 返回使用ThreadLocalRandom的UUID,比默认的UUID性能更优 */ public static UUID fastUUID() { ThreadLocalRandom random = ThreadLocalRandom.current(); return new UUID(random.nextLong(), random.nextLong()); } }
随机生成前缀 + 日期 + 后缀随机5位数
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 生成随机单据号的实现示例的文章就介绍到这了,更多相关Java 生成随机单据号内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!