自定义生成流水号

生成一个时间戳+前缀+序号

@RestController
public class LiuShuiController {

    private static int sequence = 0;

    private static AtomicInteger sequenceint = new AtomicInteger(0);

    //http://localhost:8888/getnumber
    @RequestMapping("/getnumber")
    public String getNumber(){
        //生成一个时间戳+前缀+序号  serial number

        String prefix = "sn";
        long l = System.currentTimeMillis();
        System.out.println(l);

        Calendar currentCalendar = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");  // 指定日期时间格式
        String formattedDateTime = sdf.format(currentCalendar.getTime());  // 格式化日期时间为指定格式

        //使用AtomicInteger类可以确保递增操作的原子性,避免了多线程环境下的并发问题
        AtomicLong atomicLong = new AtomicLong(0);
        atomicLong.incrementAndGet();// 递增操作

        System.out.println(atomicLong);

        int next = getNext();

        int nextAI = getNextAI();

        String format = String.format("%06d", nextAI);

        StstusCode
        return prefix+"="+formattedDateTime+"="+format;
    }


    public static synchronized int getNext(){
        return sequence++;
    }

    public static synchronized int getNextAI(){
        return sequenceint.getAndIncrement();
    }
}    

你可能感兴趣的:(java)