Several ways to generate unique id in Java (verified)

1. Database self-increasing sequence method The
database method is relatively simple, for example, oracle can use sequence to generate id, AUTO_INCREMENT in Mysql, etc., so that unique ID can be generated, performance and stability depend on the database! For example, the mysql primary key is incremented:
Insert picture description here
2. The system timestamp
can be up to 1,000 times per second. If it is a single web system cluster deployment method, you can add a logo to each machine! (It is not recommended to use a large amount of concurrent)

   /**
     * 根据时间戳生成唯一id
     */
    @Test
    public void test(){
    
    
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSSS");
        String id = sdf.format(System.currentTimeMillis());
        System.out.println("id:"+id);
        //id:202010221400070793
    }

3. UUID
uuid generates a global unique id, simple and crude to generate, local generation, no network overhead, high efficiency; but the length is long and irregular, and it is not easy to maintain! (Not recommended as a database primary key)

    /**
     * 用uuid生成为id
     */
    @Test
    public void testUUID(){
    
    
        String uuid = UUID.randomUUID().toString();
        System.out.println("uuid:"+uuid);
        //uuid:49abc3f3-d6cc-4401-b24a-0fc808d1b594
    }

4.
SnowFlake algorithm SnowFlake algorithm generates a Long type with a size of 64bit,
locally generated, no network overhead, high efficiency, but depends on the machine clock

public class SnowflakeIdWorker {
    
    

    // ==============================Fields===========================================
    /** 开始时间截 (2015-01-01) */
    private final long twepoch = 1420041600000L;

    /** 机器id所占的位数 */
    private final long workerIdBits = 5L;

    /** 数据标识id所占的位数 */
    private final long datacenterIdBits = 5L;

    /** 支持的最大机器id,结果是31 (这个移位算法可以很快的计算出几位二进制数所能表示的最大十进制数) */
    private final long maxWorkerId = -1L ^ (-1L << workerIdBits);

    /** 支持的最大数据标识id,结果是31 */
    private final long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);

    /** 序列在id中占的位数 */
    private final long sequenceBits = 12L;

    /** 机器ID向左移12位 */
    private final long workerIdShift = sequenceBits;

    /** 数据标识id向左移17位(12+5) */
    private final long datacenterIdShift = sequenceBits + workerIdBits;

    /** 时间截向左移22位(5+5+12) */
    private final long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;

    /** 生成序列的掩码,这里为4095 (0b111111111111=0xfff=4095) */
    private final long sequenceMask = -1L ^ (-1L << sequenceBits);

    /** 工作机器ID(0~31) */
    private long workerId;

    /** 数据中心ID(0~31) */
    private long datacenterId;

    /** 毫秒内序列(0~4095) */
    private long sequence = 0L;

    /** 上次生成ID的时间截 */
    private long lastTimestamp = -1L;

    //==============================Constructors=====================================
    /**
     * 构造函数
     * @param workerId 工作ID (0~31)
     * @param datacenterId 数据中心ID (0~31)
     */
    public SnowflakeIdWorker(long workerId, long datacenterId) {
    
    
        if (workerId > maxWorkerId || workerId < 0) {
    
    
            throw new IllegalArgumentException(String.format
            ("worker Id can't be greater than %d or less than 0", maxWorkerId));
        }
        if (datacenterId > maxDatacenterId || datacenterId < 0) {
    
    
            throw new IllegalArgumentException(String.format
            ("datacenter Id can't be greater than %d or less than 0", maxDatacenterId));
        }
        this.workerId = workerId;
        this.datacenterId = datacenterId;
    }

    // ==============================Methods==========================================
    /**
     * 获得下一个ID (该方法是线程安全的)
     * @return SnowflakeId
     */
    public synchronized long nextId() {
    
    
        long timestamp = timeGen();

        //如果当前时间小于上一次ID生成的时间戳,说明系统时钟回退过这个时候应当抛出异常
        if (timestamp < lastTimestamp) {
    
    
            throw new RuntimeException(
                    String.format
                    ("Clock moved backwards.  Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
        }

        //如果是同一时间生成的,则进行毫秒内序列
        if (lastTimestamp == timestamp) {
    
    
            sequence = (sequence + 1) & sequenceMask;
            //毫秒内序列溢出
            if (sequence == 0) {
    
    
                //阻塞到下一个毫秒,获得新的时间戳
                timestamp = tilNextMillis(lastTimestamp);
            }
        }
        //时间戳改变,毫秒内序列重置
        else {
    
    
            sequence = 0L;
        }

        //上次生成ID的时间截
        lastTimestamp = timestamp;

        //移位并通过或运算拼到一起组成64位的ID
        return ((timestamp - twepoch) << timestampLeftShift) //
                | (datacenterId << datacenterIdShift) //
                | (workerId << workerIdShift) //
                | sequence;
    }

    /**
     * 阻塞到下一个毫秒,直到获得新的时间戳
     * @param lastTimestamp 上次生成ID的时间截
     * @return 当前时间戳
     */
    protected long tilNextMillis(long lastTimestamp) {
    
    
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
    
    
            timestamp = timeGen();
        }
        return timestamp;
    }

    /**
     * 返回以毫秒为单位的当前时间
     * @return 当前时间(毫秒)
     */
    protected long timeGen() {
    
    
        return System.currentTimeMillis();
    }

    //==============================Test=============================================
    /** 测试 */
    public static void main(String[] args) {
    
    
        SnowflakeIdWorker idWorker = new SnowflakeIdWorker(0, 0);
        long id = idWorker.nextId();
        System.out.println("id:"+id);
        //id:768842202204864512
    }
}

5. Redis generates a global unique id
based on the atomic characteristics of redis single thread to generate a global unique id. Redis has high performance and supports cluster sharding. The only drawback is that it relies on the redis service (recommended) to
implement the process (core code):


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.Calendar;
import java.util.Date;

/**
 * @author xf
 * @version 1.0.0
 * @ClassName PrimaryKeyUtil
 * @Description TODO 利用redis生成数据库全局唯一性id
 * @createTime 2020.10.22 10:42
 */
@Service
public class PrimaryKeyUtil {
    
    

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 获取年的后两位加上一年多少天+当前小时数作为前缀
     * @param date
     * @return
     */
    public String getOrderIdPrefix(Date date) {
    
    
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        //String.format("%1$02d", var)
        // %后的1指第一个参数,当前只有var一个可变参数,所以就是指var。
        // $后的0表示,位数不够用0补齐,如果没有这个0(如%1$nd)就以空格补齐,0后面的n表示总长度,总长度可以可以是大于9例如(%1$010d),d表示将var按十进制转字符串,长度不够的话用0或空格补齐。
        String monthFormat = String.format("%1$02d", month+1);
        String dayFormat = String.format("%1$02d", day);
        String hourFormat = String.format("%1$02d", hour);

        return year + monthFormat + dayFormat+hourFormat;
    }

    /**
     * 生成订单号
     * @param prefix
     * @return
     */
    public Long orderId(String prefix) {
    
    
        String key = "ORDER_ID_" + prefix;
        String orderId = null;
        try {
    
    
            Long increment = redisTemplate.opsForValue().increment(key,1);
            //往前补6位
            orderId=prefix+String.format("%1$06d",increment);
        } catch (Exception e) {
    
    
            System.out.println("生成单号失败");
            e.printStackTrace();
        }
        return Long.valueOf(orderId);
    }

}

Test redis to generate a unique id, it takes 514 milliseconds to generate 1000

import com.king.science.util.PrimaryKeyUtil;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.Date;

/**
 * 测试类
 */
@SpringBootTest
class ScienceApplicationTests {
    
    

    @Autowired
    private PrimaryKeyUtil primaryKeyUtil;

    /**
     * 使用redis生成唯一id
     */
    @Test
    public void testRedis() {
    
    
        long startMillis = System.currentTimeMillis();
        String orderIdPrefix = primaryKeyUtil.getOrderIdPrefix(new Date());
        //生成单个id
        //Long aLong = primaryKeyUtil.orderId(orderIdPrefix);
        for (int i = 0; i < 1000; i++) {
    
    
            Long aLong = primaryKeyUtil.orderId(orderIdPrefix);
            System.out.println(aLong);
        }
        long endMillis = System.currentTimeMillis();
        System.out.println("测试生成1000个使用时间:"+(endMillis-startMillis)+",单位毫秒");
        //测试生成1000个使用时间:514,单位毫秒
    }

}

Insert picture description here
Redis totals incr1000 times. The
Insert picture description here
above are the five ways to generate unique IDs summarized this time. What way do you use in your project?

Guess you like

Origin blog.csdn.net/weixin_44146379/article/details/109220528
Recommended