欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java生成固定位数,随机数,纯数字,不重复,简单。

程序员文章站 2022-07-10 20:56:59
import java.util.Random;public class NumberGenerator { public NumberGenerator() { } public static long getNumber(int length) { StringBuilder buf = new StringBuilder(); Random random = new Random(); int firstNumber =.....

import java.util.Random;

public class NumberGenerator {
    public NumberGenerator() {
    }
    //随机数工具方法
    public static long getNumber(int length) {
        StringBuilder buf = new StringBuilder();
        Random random = new Random();
        int firstNumber = random.nextInt(9) + 1; //开头不为0
        buf.append(firstNumber);

        for(int i = 0; i < length - 1; ++i) {
            buf.append(random.nextInt(10));
        }

        return Long.valueOf(buf.toString());
    }
}
mybatis-plus service:

@Override
@Transactional(propagation = Propagation.REQUIRES_NEW)//脱离业务事务,开启新事务
private String getNumber(int length, int numberType) {
        String number = null;
        ResourceNumber resourceNumber = new ResourceNumber();
        //最多尝试10次
        for (int time = 0; time < 10; time++) {
            try {
                long userNumberL = NumberGenerator.getNumber(length);
                resourceNumber.setNumber(userNumberL);
         

本文地址:https://blog.csdn.net/z125499702/article/details/107465484