生成24位字符串ID__IdGenerator.java

本文介绍了一个用于生成24位唯一字符串ID的工具类。该ID由时间戳、机器标识和序列号组成,确保了ID的全局唯一性。文章提供了完整的Java实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

此工具类用于生成24位字符串ID,唯一不重复。
直接通过 IdGenerator.get() 获取。

 

源码如下:(点击下载源码 - IdGenerator.java )

import java.net.NetworkInterface;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Enumeration;

/**
 * 生成24位字符串ID
 * 
 */
public class IdGenerator implements Comparable<IdGenerator> {

    /**
     * 调用该方法获取24位字符串ID
     * @return
     */
    public static String get() {
        return new IdGenerator().toString();
    }

    public IdGenerator() {
        _time = _gentime;
        _machine = _genmachine;
        synchronized (_incLock) {
            _inc = _nextInc++;
        }
        _new = true;
    }

    public int hashCode() {
        return _inc;
    }

    public String toStringMongod() {
        byte b[] = toByteArray();

        StringBuilder buf = new StringBuilder(24);

        for (int i = 0; i < b.length; i++) {
            int x = b[i] & 0xFF;
            String s = Integer.toHexString(x);
            if (s.length() == 1)
                buf.append("0");
            buf.append(s);
        }

        return buf.toString();
    }

    public byte[] toByteArray() {
        byte b[] = new byte[12];
        ByteBuffer bb = ByteBuffer.wrap(b);
        bb.putInt(_inc);
        bb.putInt(_machine);
        bb.putInt(_time);
        reverse(b);
        return b;
    }

    static void reverse(byte[] b) {
        for (int i = 0; i < b.length / 2; i++) {
            byte t = b[i];
            b[i] = b[b.length - (i + 1)];
            b[b.length - (i + 1)] = t;
        }
    }

    static String _pos(String s, int p) {
        return s.substring(p * 2, (p * 2) + 2);
    }

    public String toString() {
        return toStringMongod();
    }

    public int compareTo(IdGenerator id) {
        if (id == null)
            return -1;

        long xx = id.getTime() - getTime();
        if (xx > 0)
            return -1;
        else if (xx < 0)
            return 1;

        int x = id._machine - _machine;
        if (x != 0)
            return -x;

        x = id._inc - _inc;
        if (x != 0)
            return -x;

        return 0;
    }

    public int getMachine() {
        return _machine;
    }

    public long getTime() {
        long z = _flip(_time);
        return z * 1000;
    }

    public int getInc() {
        return _inc;
    }

    final int _time;
    final int _machine;
    final int _inc;

    boolean _new;

    static int _flip(int x) {
        byte b[] = new byte[4];
        ByteBuffer bb = ByteBuffer.wrap(b);
        bb.order(ByteOrder.LITTLE_ENDIAN);
        bb.putInt(x);
        bb.flip();
        bb.order(ByteOrder.BIG_ENDIAN);
        return bb.getInt();
    }

    private static int _nextInc = (new java.util.Random()).nextInt();
    private static final String _incLock = new String("IdGenerator._incLock");

    private static int _gentime = _flip((int) (System.currentTimeMillis() / 1000));

    static final Thread _timeFixer;
    private static final int _genmachine;
    static {
        try {
            final int machinePiece;
            {
                StringBuilder sb = new StringBuilder();
                Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();
                while (e.hasMoreElements()) {
                    NetworkInterface ni = e.nextElement();
                    sb.append(ni.toString());
                }
                machinePiece = sb.toString().hashCode() << 16;
            }

            final int processPiece = java.lang.management.ManagementFactory.getRuntimeMXBean().getName().hashCode() & 0xFFFF;
            _genmachine = machinePiece | processPiece;
        } catch (java.io.IOException ioe) {
            throw new RuntimeException(ioe);
        }

        _timeFixer = new Thread("IdGenerator-TimeFixer") {
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(499);
                    } catch (InterruptedException e) {
                    }
                    _gentime = _flip((int) (System.currentTimeMillis() / 1000));
                }
            }
        };
        _timeFixer.setDaemon(true);
        _timeFixer.start();
    }

}

 

转载于:https://www.cnblogs.com/lr393993507/p/5457437.html

已知nacos部分配置如下:disk_my_info: # 动态表名占符,根据user_id的值决定实际表名 actual-data-nodes: master.disk_my_info_$->{1..9999} # 数据分片策略 table-strategy: # 标准分片策略 standard: # 用于分片的列名 sharding-column: create_uid # 使用的分片算法名称 sharding-algorithm-name: user-id-inline # 主键生成策略 key-generate-strategy: # 主键列名 column: id # 使用的主键生成器名称,使用雪花策略 key-generator-name: snowflake ,其执行的mapper如下 List<DiskMyInfoDto> selectShareFileByReceiveIdWithCreateUid(@Param("createUid")Long createUid,@Param("userId")Long userId); ,sql片段如下:<select id="selectShareFileByReceiveIdWithCreateUid" parameterType="map" resultMap="DiskMyInfoAndReceiveShareResult"> SELECT DISTINCT myInfo.id, myInfo.file_id, myInfo.client_file_name, myInfo.client_file_location, myInfo.is_dir, myInfo.is_back_up, myInfo.file_type, myInfo.file_size, myInfo.parent_id, myInfo.root_id, myInfo.id_seq, myInfo.file_sort, myInfo.file_source, myInfo.file_status, '-1' AS is_share, myInfo.is_receive, myInfo.receive_id, myInfo.file_md5, myInfo.create_uid, myInfo.create_by, myInfo.create_time, myInfo.update_uid, myInfo.update_by, myInfo.update_time, myShare.content_can_modify, myShare.share_end_time, usr.real_name AS share_create_by_name FROM disk_my_share_info myShare INNER JOIN disk_my_info myInfo ON myShare.file_id = myInfo.id and myInfo.create_uid = #{createUid} LEFT JOIN t_sys_user usr ON usr.user_name = myShare.create_by WHERE myShare.file_id IS NOT NULL AND ( myShare.share_user_id = 'ALL' OR myShare.share_user_id like concat('%.',#{userId},'.%') ) AND myShare.is_enabled = '1' AND myInfo.create_uid = #{createUid} </select>,出现错误如下### The error occurred while setting parameters ### SQL: SELECT DISTINCT myInfo.id, myInfo.file_id, myInfo.client_file_name, myInfo.client_file_location, myInfo.is_dir, myInfo.is_back_up, myInfo.file_type, myInfo.file_size, myInfo.parent_id, myInfo.root_id, myInfo.id_seq, myInfo.file_sort, myInfo.file_source, myInfo.file_status, '-1' AS is_share, myInfo.is_receive, myInfo.receive_id, myInfo.file_md5, myInfo.create_uid, myInfo.create_by, myInfo.create_time, myInfo.update_uid, myInfo.update_by, myInfo.update_time, myShare.content_can_modify, myShare.share_end_time, usr.real_name AS share_create_by_name FROM disk_my_share_info myShare INNER JOIN disk_my_info myInfo ON myShare.file_id = myInfo.id and myInfo.create_uid = ? LEFT JOIN t_sys_user usr ON usr.user_name = myShare.create_by WHERE myShare.file_id IS NOT NULL AND ( myShare.share_user_id = 'ALL' OR myShare.share_user_id like concat('%.',?,'.%') ) AND myShare.is_enabled = '1' AND myInfo.create_uid = ? ### Cause: java.sql.SQLException: Error while preparing statement [SELECT DISTINCT myInfo.id, myInfo.file_id, myInfo.client_file_name, myInfo.client_file_location, myInfo.is_dir, myInfo.is_back_up, myInfo.file_type, myInfo.file_size, myInfo.parent_id, myInfo.root_id, myInfo.id_seq, myInfo.file_sort, myInfo.file_source, myInfo.file_status, '-1' AS is_share, myInfo.is_receive, myInfo.receive_id, myInfo.file_md5, myInfo.create_uid, myInfo.create_by, myInfo.create_time, myInfo.update_uid, myInfo.update_by, myInfo.update_time, myShare.content_can_modify, myShare.share_end_time, usr.real_name AS share_create_by_name FROM disk_my_share_info myShare INNER JOIN disk_my_info myInfo ON myShare.file_id = myInfo.id and myInfo.create_uid = ? LEFT JOIN t_sys_user usr ON usr.user_name = myShare.create_by WHERE myShare.file_id IS NOT NULL AND ( myShare.share_user_id = 'ALL' OR myShare.share_user_id like concat('%.',?,'.%') ) AND myShare.is_enabled = '1' AND myInfo.create_uid = ?] ; uncategorized SQLException; SQL state [null]; error code [0];
最新发布
07-10
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值