生成永不重复的分布式ID

1,715 阅读1分钟

引言:更多相关请看 Java其它
代码如下:

@Slf4j
public class IdGenerateUtil {

    /**
     * 获取ID
     *
     * @param length 随机长度 默认是21位
     * @return
     */
    public static String getPrivateId(Integer length) {
        // 时间戳
        String value = String.valueOf(System.currentTimeMillis());

        // UUID
        String uuid = UUID.randomUUID().toString();

        String result = uuid.substring(0, 7) + value.substring(value.length() - 6, value.length() - 1) + uuid.substring(uuid.length() - 10, uuid.length() - 1);
        if (length != null || length != 0) {
            return result.substring(0, length);
        }
        return result;
    }

    /**
     * 返回不重复的主键ID
     * @param list 任意list对象
     * @param length 密码长度,不给默认返回21位
     * @param key 需要比较统计的key(对象字段名称)
     * @return
     */
    public static String getNoRepeatId(List list, Integer length, String key) {
        String orderId = getPrivateId(length);// 调用生成的key
        log.info("生成的ID结果:{}", orderId);
        if (list == null || list.size() == 0) {
            return orderId;
        }
        // 如果有包含说明重复,返回
        if (list != null) {
            final String order = orderId;
            /**
             * 把列表的所有对象迭代出来,BeanUtil方法把对象转为Map,map的key是字段名称,value是字段值。
             * 通过key(主键ID或其他字段名,比如tradeId)获取value,与生成的ID进行比较是否相等。
             * count()统计相等的值的数量,
             * cn.hutool.core.bean.BeanUtil:把对象转为Map
             */
            long count = list.stream().filter(o -> null != o && null != BeanUtil.beanToMap(o) && null != BeanUtil.beanToMap(o).get(key)
                    && BeanUtil.beanToMap(o).get(key).equals(order)).count();
            // 如果大于等于1,就递归调用生成新的ID,并再次迭代循环比较统计,直到生成的ID不再重复为止
            if (count >= 1) {
                orderId = getNoRepeatId(list, length, key);
            }
        }
        return orderId;
    }
}