Java-生成唯一ID(Sequence)

package com.bootdo.common.utils;

import org.springframework.stereotype.Component;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author 张子布
 * @version 1.0
 * @date 2018/8/28
 * @explain:
 */
@Component
public class Sequence {
    private static final long ONE_STEP = 10;
    private static final Lock LOCK = new ReentrantLock();
    private static long lastTime = System.currentTimeMillis();
    private static short lastCount = 0;
    private static int count = 0;

    @SuppressWarnings("finally")
    public static String nextId() {
        LOCK.lock();
        try {
            if (lastCount == ONE_STEP) {
                boolean done = false;
                while (!done) {
                    long now = System.currentTimeMillis();
                    if (now == lastTime) {
                        try {
                            Thread.currentThread();
                            Thread.sleep(1);
                        } catch (java.lang.InterruptedException e) {
                        }
                        continue;
                    } else {
                        lastTime = now;
                        lastCount = 0;
                        done = true;
                    }
                }
            }
            count = lastCount++;
        } finally {
            LOCK.unlock();
            return lastTime + "" + String.format("%03d", count);
        }
    }

    //获得batchNo批次号
    @SuppressWarnings({"finally"})
    public static String getBatchNo() {
        LOCK.lock();
        try {
            if (lastCount == ONE_STEP) {
                boolean done = false;
                while (!done) {
                    long now = System.currentTimeMillis();
                    if (now == lastTime) {
                        try {
                            Thread.currentThread();
                            Thread.sleep(1);
                        } catch (java.lang.InterruptedException e) {
                        }
                        continue;
                    } else {
                        lastTime = now;
                        lastCount = 0;
                        done = true;
                    }
                }
            }
            count = lastCount++;
        } finally {
            LOCK.unlock();
            String str = lastTime + "" + String.format("%03d", count);
            String batchNo = "C"+str.substring(1);
            return batchNo;
        }
    }

    public static void main(String[] args) {
        //测试

            System.out.println(nextId());

    }
}
Java中,可以使用以下几种方式来实现生成唯一ID: 1. UUID(Universally Unique Identifier):UUID是一种标准的128位唯一标识符,可以通过Java的UUID类来生成。UUID生成算法保证了生成ID在全球范围内是唯一的,但是它的字符串形式比较长。 示例代码: ```java import java.util.UUID; public class UniqueIdGenerator { public static String generateUniqueId() { UUID uuid = UUID.randomUUID(); return uuid.toString(); } } ``` 2. Snowflake算法:Snowflake算法是Twitter开源的一种分布式ID生成算法,它可以生成一个64位的唯一ID。Snowflake算法的核心思想是将一个64位的ID分成多个部分,每个部分表示不同的信息,如时间戳、机器ID、序列号等。 示例代码: ```java public class UniqueIdGenerator { private static final long START_TIMESTAMP = 1622505600000L; // 设置起始时间戳,如2021-06-01 00:00:00 private static final long MACHINE_ID = 1L; // 设置机器ID,范围为0-1023 private static long sequence = 0L; private static long lastTimestamp = -1L; public static synchronized long generateUniqueId() { long currentTimestamp = System.currentTimeMillis(); if (currentTimestamp < lastTimestamp) { throw new RuntimeException("Clock moved backwards. Refusing to generate id."); } if (currentTimestamp == lastTimestamp) { sequence = (sequence + 1) & 4095; // 序列号部分取值范围为0-4095 if (sequence == 0) { currentTimestamp = tilNextMillis(lastTimestamp); } } else { sequence = 0L; } lastTimestamp = currentTimestamp; long id = ((currentTimestamp - START_TIMESTAMP) << 22) | (MACHINE_ID << 12) | sequence; return id; } private static long tilNextMillis(long lastTimestamp) { long timestamp = System.currentTimeMillis(); while (timestamp <= lastTimestamp) { timestamp = System.currentTimeMillis(); } return timestamp; } } ``` 这些是Java中常用的生成唯一ID的方式,你可以根据具体的需求选择合适的方式来生成唯一ID
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值