溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

java如何使用預(yù)分配法生成唯一ID

發(fā)布時(shí)間:2021-12-29 09:25:02 來源:億速云 閱讀:170 作者:小新 欄目:軟件技術(shù)

小編給大家分享一下java如何使用預(yù)分配法生成唯一ID,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

在項(xiàng)目中經(jīng)常有生成唯一ID的業(yè)務(wù)需求。作為唯一標(biāo)識(shí)方便后續(xù)查找和追蹤。網(wǎng)上也有很多實(shí)現(xiàn)方案。比如:數(shù)據(jù)庫自增主鍵,數(shù)據(jù)庫批量生成ID,UUID,時(shí)間戳方法,zookeeper生成ID,redis生成唯一ID,snowflake算法等等。這些解決方案各有優(yōu)缺點(diǎn)。我在游戲項(xiàng)目常用的解決方案是:預(yù)分配法生成唯一ID。其原理簡(jiǎn)單,利于擴(kuò)展,具有較強(qiáng)的適用性。

預(yù)分配法生成唯一ID原理:數(shù)據(jù)庫中存儲(chǔ)每種類型最后的預(yù)分配dbUniqueId值。數(shù)據(jù)庫實(shí)體對(duì)象上增加當(dāng)前分配的
useDbUniqueId。預(yù)分配步長(zhǎng)DBUNIQUEID_M可根據(jù)類型和業(yè)務(wù)量自定義。當(dāng)useDbUniqueId大于等于dbUniqueId時(shí)就預(yù)分配出DBUNIQUEID_M個(gè)唯一ID。

角色I(xiàn)D生成:要求7位連續(xù)的唯一ID。則DBUNIQUEID_M=1。1000000+dbUniqueId格式化成7位數(shù)字。

本服唯一ID:則DBUNIQUEID_M=10000。(1000000+dbUniqueId)*10000+serverId格式化而成。其中serverId游戲服ID定義為4位

全局唯一ID:則DBUNIQUEID_M=10000。((100000000000L+dbUniqueId)100+gameCode10000+workerId;格式化而成。其中g(shù)ameCode游戲編碼定義為2位。

具體實(shí)現(xiàn)請(qǐng)參閱代碼。非常方便的移植到項(xiàng)目工程中。

IdWorkerEnum.java

package com.game.common.db;
import java.util.List;
import com.core.enums.LLIndexedEnum;
/**
 * ID枚舉類型
 * @author Thinker
 */
public enum IdWorkerEnum implements LLIndexedEnum
{
    /** 角色I(xiàn)D */
    IDWORKER_HUMANID(1,"角色I(xiàn)D"),
    /** 數(shù)據(jù)庫ID */
    IDWORKER_DBID(2,"數(shù)據(jù)庫ID"),
    /** 工會(huì)ID */
    IDWORKER_CLUBID(3,"工會(huì)ID"),
    /** 收集ID */
    IDWORKER_COLLECTID(4,"收集ID"),;
    /** 枚舉的索引 */
    public final int index;
    /** 名稱的key */
    private final String nameKey;
    /** 按索引順序存放的枚舉數(shù)組 */
    private static final List<IdWorkerEnum> indexes=LLIndexedEnum.IndexedEnumUtil.toIndexes(IdWorkerEnum.values());
    private IdWorkerEnum(int index,String nameKey)
    {
        this.index=index;
        this.nameKey=nameKey;
    }
    /**
     * 獲取索引
     */
    @Override
    public int getIndex()
    {
        return index;
    }
    /**
     * 取得名稱key
     */
    public String getNameKey()
    {
        return this.nameKey;
    }
    /**
     * 根據(jù)指定的索引獲取枚舉的定義
     */
    public static IdWorkerEnum valueOf(final int index)
    {
        return LLIndexedEnum.IndexedEnumUtil.valueOf(indexes,index);
    }
}

DbUniqueIdEntity.java

package com.game.common.db;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import org.eclipse.persistence.annotations.HashPartitioning;
import org.eclipse.persistence.annotations.Partitioned;
import com.game.common.db.dao.BaseDbBean;
/**
 * 數(shù)據(jù)庫唯一KEY實(shí)體類
 * @author Thinker
 */
@Entity(name="t_dbUniqueId")
@HashPartitioning(name="HashPartitionByDbUniqueCacheId",partitionColumn=@Column(name="dbUniqueCacheId"))
@Partitioned("HashPartitionByDbUniqueCacheId")
public class DbUniqueIdEntity extends BaseDbBean
{
    /** 數(shù)據(jù)庫唯一緩存ID **/
    @Id
    @Column(length=20)
    private long dbUniqueCacheId;
    /** 數(shù)據(jù)庫唯一ID **/
    @Column(length=20)
    private long dbUniqueId;
    /** 最后更新的時(shí)間 **/
    @Column(length=20)
    private long createTime;
    // ////////////////內(nèi)部數(shù)據(jù)//////////////////
    /** 已經(jīng)使用過的數(shù)據(jù)庫唯一ID(唯一ID) */
    @Column(length=20)
    private long useDbUniqueId;
    @Override
    public long getId()
    {
        return dbUniqueCacheId;
    }
    @Override
    public void setId(long id)
    {
    }
    public long getDbUniqueCacheId()
    {
        return dbUniqueCacheId;
    }
    public void setDbUniqueCacheId(long dbUniqueCacheId)
    {
        this.dbUniqueCacheId=dbUniqueCacheId;
    }
    public long getDbUniqueId()
    {
        return dbUniqueId;
    }
    public void setDbUniqueId(long dbUniqueId)
    {
        this.dbUniqueId=dbUniqueId;
    }
    public long getCreateTime()
    {
        return createTime;
    }
    public void setCreateTime(long createTime)
    {
        this.createTime=createTime;
    }
    public long getUseDbUniqueId()
    {
        return useDbUniqueId;
    }
    public void setUseDbUniqueId(long useDbUniqueId)
    {
        this.useDbUniqueId=useDbUniqueId;
    }
}

IdWorker.java

package com.game.common.db;
import com.game.common.Globals;
import com.game.common.entityProxy.EntityProxy;
import com.game.core.appConfig.AppConfigServ;
import com.game.core.utils.LoggerUtils;
/**
 * 唯一ID生成器
 * 
 * @author Thinker
 */
public class IdWorker
{
    public final static IdWorker OBJ=new IdWorker(AppConfigServ.OBJ.getAppConfigBean().getServerNo());
    private int DBUNIQUEID_M=2000;
    private final long workerId;
    /** 數(shù)據(jù)庫連接池 */
    private DbUniqueIdEntity[] szDbUniqueIdEntity=new DbUniqueIdEntity[5];
    public IdWorker(long workerId)
    {
        this.workerId=workerId;
    }
    /**
     * 生成系統(tǒng)唯一ID:采用隱性鎖方式
     */
    public synchronized long nextId()
    {
        IdWorkerEnum idWorkerEnum=IdWorkerEnum.IDWORKER_DBID;
        int dbUniqueCacheId=idWorkerEnum.getIndex();
        loadDbUniqueId(idWorkerEnum);
        DbUniqueIdEntity dbUniqueIdEntity=szDbUniqueIdEntity[dbUniqueCacheId];
        long dbUniqueId=0;
        // 需要重新分配Id:每次分配 M個(gè)
        if(dbUniqueIdEntity.getUseDbUniqueId()>=dbUniqueIdEntity.getDbUniqueId())
        {
            dbUniqueIdEntity.setDbUniqueId(dbUniqueIdEntity.getDbUniqueId()+DBUNIQUEID_M);
            EntityProxy.OBJ.update((long) dbUniqueCacheId,dbUniqueIdEntity);
            LoggerUtils.serverLogger.info("IdWorker DbId:update dbUniqueId="+dbUniqueIdEntity.getDbUniqueId());
        }
        dbUniqueId=dbUniqueIdEntity.getUseDbUniqueId()+1;
        dbUniqueIdEntity.setUseDbUniqueId(dbUniqueId);
        // 11位UUID
        return (1000000+dbUniqueId)*10000+workerId;
    }
    /**
     * 生成系統(tǒng)唯一HumanID:采用隱性鎖方式
     */
    public synchronized long nextHumanId()
    {
        IdWorkerEnum idWorkerEnum=IdWorkerEnum.IDWORKER_HUMANID;
        int dbUniqueCacheId=idWorkerEnum.getIndex();
        loadDbUniqueId(idWorkerEnum);
        DbUniqueIdEntity dbUniqueIdEntity=szDbUniqueIdEntity[dbUniqueCacheId];
        long dbUniqueId=0;
        // 需要重新分配Id:每次分配 M個(gè)
        if(dbUniqueIdEntity.getUseDbUniqueId()>=dbUniqueIdEntity.getDbUniqueId())
        {
            dbUniqueIdEntity.setDbUniqueId(dbUniqueIdEntity.getDbUniqueId()+1);
            EntityProxy.OBJ.update((long) dbUniqueCacheId,dbUniqueIdEntity);
            LoggerUtils.serverLogger.info("IdWorker HumanId:update dbUniqueId="+dbUniqueIdEntity.getDbUniqueId());
        }
        dbUniqueId=dbUniqueIdEntity.getUseDbUniqueId()+1;
        dbUniqueIdEntity.setUseDbUniqueId(dbUniqueId);
        // 7位UUID
        return (1000000+dbUniqueId);
    }
    /**
     * 生成系統(tǒng)唯一ClubID:采用隱性鎖方式
     */
    public synchronized long nextClubId()
    {
        IdWorkerEnum idWorkerEnum=IdWorkerEnum.IDWORKER_CLUBID;
        int dbUniqueCacheId=idWorkerEnum.getIndex();
        loadDbUniqueId(idWorkerEnum);
        DbUniqueIdEntity dbUniqueIdEntity=szDbUniqueIdEntity[dbUniqueCacheId];
        long dbUniqueId=0;
        // 需要重新分配Id:每次分配 M個(gè)
        if(dbUniqueIdEntity.getUseDbUniqueId()>=dbUniqueIdEntity.getDbUniqueId())
        {
            dbUniqueIdEntity.setDbUniqueId(dbUniqueIdEntity.getDbUniqueId()+1);
            EntityProxy.OBJ.update((long) dbUniqueCacheId,dbUniqueIdEntity);
            LoggerUtils.serverLogger.info("IdWorker clubId:update dbUniqueId="+dbUniqueIdEntity.getDbUniqueId());
        }
        dbUniqueId=dbUniqueIdEntity.getUseDbUniqueId()+1;
        dbUniqueIdEntity.setUseDbUniqueId(dbUniqueId);
        // 5位UUID
        return (10000+dbUniqueId);
    }
    /**
     * 生成系統(tǒng)唯一ID:采用隱性鎖方式
     */
    public synchronized long nextCollectId()
    {
        IdWorkerEnum idWorkerEnum=IdWorkerEnum.IDWORKER_COLLECTID;
        int dbUniqueCacheId=idWorkerEnum.getIndex();
        loadDbUniqueId(idWorkerEnum);
        DbUniqueIdEntity dbUniqueIdEntity=szDbUniqueIdEntity[dbUniqueCacheId];
        long dbUniqueId=0;
        // 需要重新分配Id:每次分配 M個(gè)
        if(dbUniqueIdEntity.getUseDbUniqueId()>=dbUniqueIdEntity.getDbUniqueId())
        {
            dbUniqueIdEntity.setDbUniqueId(dbUniqueIdEntity.getDbUniqueId()+DBUNIQUEID_M);
            EntityProxy.OBJ.update((long) dbUniqueCacheId,dbUniqueIdEntity);
            LoggerUtils.serverLogger.info("IdWorker DbId:update dbUniqueId="+dbUniqueIdEntity.getDbUniqueId());
        }
        dbUniqueId=dbUniqueIdEntity.getUseDbUniqueId()+1;
        dbUniqueIdEntity.setUseDbUniqueId(dbUniqueId);
        // 18位UUID:游戲ID+服務(wù)器ID。確保支持多游戲不重復(fù)的ID。便于兼容統(tǒng)計(jì)
        return ((100000000000L+dbUniqueId)*100+AppConfigServ.OBJ.getAppConfigBean().getGameCode())*10000+workerId;
    }
    /**
     * 加載唯一ID
     */
    public void loadDbUniqueId(IdWorkerEnum idWorkerEnum)
    {
        int dbUniqueCacheId=idWorkerEnum.getIndex();
        if(szDbUniqueIdEntity[dbUniqueCacheId]!=null) return;
        DbUniqueIdEntity dbUniqueIdEntity=EntityProxy.OBJ.get((long) dbUniqueCacheId,(long) dbUniqueCacheId,DbUniqueIdEntity.class);
        if(dbUniqueIdEntity==null)
        {
            dbUniqueIdEntity=new DbUniqueIdEntity();
            dbUniqueIdEntity.setDbUniqueCacheId(dbUniqueCacheId);
            dbUniqueIdEntity.setDbUniqueId(0);
            dbUniqueIdEntity.setCreateTime(Globals.getTimeService().now());
            dbUniqueIdEntity.setUseDbUniqueId(0);
            EntityProxy.OBJ.insert((long) dbUniqueCacheId,dbUniqueIdEntity);
        }
        dbUniqueIdEntity.setUseDbUniqueId(dbUniqueIdEntity.getDbUniqueId());
        szDbUniqueIdEntity[dbUniqueCacheId]=dbUniqueIdEntity;
        LoggerUtils.serverLogger.info("IdWorker:load dbUniqueId="+dbUniqueIdEntity.getDbUniqueId());
    }
}

以上是“java如何使用預(yù)分配法生成唯一ID”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI