001/*
002 *    Copyright 2024-2025, Warm-Flow (290631660@qq.com).
003 *
004 *    Licensed under the Apache License, Version 2.0 (the "License");
005 *    you may not use this file except in compliance with the License.
006 *    You may obtain a copy of the License at
007 *
008 *       https://www.apache.org/licenses/LICENSE-2.0
009 *
010 *    Unless required by applicable law or agreed to in writing, software
011 *    distributed under the License is distributed on an "AS IS" BASIS,
012 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 *    See the License for the specific language governing permissions and
014 *    limitations under the License.
015 */
016package org.dromara.warm.flow.core.utils;
017
018import org.dromara.warm.flow.core.FlowFactory;
019import org.dromara.warm.flow.core.constant.FlowCons;
020import org.dromara.warm.flow.core.keygen.KenGen;
021import org.dromara.warm.flow.core.keygen.SnowFlakeId14;
022import org.dromara.warm.flow.core.keygen.SnowFlakeId15;
023import org.dromara.warm.flow.core.keygen.SnowFlakeId19;
024
025/**
026 * 唯一id
027 *
028 * @author warm
029 * @since 2023/5/17 23:08
030 */
031public class IdUtils {
032
033    /** 内置id算法 */
034    private volatile static KenGen instance;
035
036    /** orm框架配置了原生id算法 */
037    private static KenGen instanceNative;
038
039    public static String nextIdStr() {
040        return nextId().toString();
041    }
042
043    public static Long nextId() {
044        return nextId(1, 1);
045    }
046
047    public static Long nextId(long workerId, long datacenterId) {
048        if (instance == null) {
049            synchronized (IdUtils.class) {
050                if (instance == null) {
051                    String keyType = FlowFactory.getFlowConfig().getKeyType();
052                    if (FlowCons.SNOWID14.equals(keyType)) {
053                        instance = new SnowFlakeId14(workerId);
054                    } else if (FlowCons.SNOWID15.equals(keyType)) {
055                        instance = new SnowFlakeId15(workerId);
056                    }
057                    if (instance == null) {
058                        // 如果orm框架配置了原生id算法,则使用原生id算法,否则默认使用19位内置雪花算法
059                        if (instanceNative != null) {
060                            instance = instanceNative;
061                        } else {
062                            instance = new SnowFlakeId19(workerId, datacenterId);
063                        }
064                    }
065                }
066            }
067        }
068        return instance.nextId();
069    }
070
071    public static void setInstanceNative(KenGen instanceNative) {
072        IdUtils.instanceNative = instanceNative;
073    }
074
075}