全域性唯一序列號生成器 支援分布式

2021-10-01 13:35:07 字數 2115 閱讀 1698

場景:在某些業務場景,需要生成唯一的序列號,來定位某乙個條資料,且必須保證全域性唯一,例如:交易流水號等。

/**

* 序列號生成服務

*/@service

public class sngenerator

public synchronized string getseq(string seqname,int length)

else

}return string.format(string.format("%%0%dd",length),seqmap.get(seqname).getseqcurrent());

}@transactional

protected void getnewfragment(string seqname)

else

logger.debug("獲取流水號段 事務結束");

}class seqfragmentdefine

public void setseqfragmentmax(long seqfragmentmax)

public long getseqcurrent()

public void setseqcurrent(long seqcurrent)

}}

public class tbl***batseqctrl extends baseentity 

public void setseqname(string seqname)

public long getseqno()

public void setseqno(long seqno)

public integer getsteplength()

public void setsteplength(integer steplength)

public date getreccrtts()

public void setreccrtts(date reccrtts)

public date getrecupdts()

public void setrecupdts(date recupdts)

}

drop table if exists tbl_***_batseq_ctrl;

create table tbl_***_batseq_ctrl (seq_name varchar(20) not null,

seq_no bigint not null comment '已經使用到的最大值(包含)',

step_length int,

rec_crt_ts timestamp default current_timestamp,

rec_upd_ts timestamp default current_timestamp on update current_timestamp,

primary key (seq_name)) engine=innodb default charset=utf8 default collate=utf8_general_ci;

string.format(string.format("%%0%dd",length),seqmap.get(seqname).getseqcurrent())

等價於string.format("%0"+length+「d」,seqmap.get(seqname).getseqcurrent())

例如: string.format("%08d",1)

輸出: 00000001

例如: string.format("%08d",-1)

輸出:-0000001

例如: string.format("%08d",200000001)

輸出:200000001 (超出長度,輸出原值)

a.每次啟動,分配步長為10000的序列號給伺服器節點使用

b.以損耗序列號資源來換取資料庫伺服器的高效能,每個節點的序列號值,不更新到資料庫

c.由於synchronized關鍵字,解決了併發問題

分布式唯一ID生成器

在應用程式中,經常需要全域性唯一的id作為資料庫主鍵。如何生成全域性唯一id?首先,需要確定全域性唯一id是整型還是字串?如果是字串,那麼現有的uuid就完全滿足需求,不需要額外的工作。缺點是字串作為id占用空間大,索引效率比整型低。如果採用整型作為id,那麼首先排除掉32位int型別,因為範圍太小...

應用id 分布式唯一ID生成器

在應用程式中,經常需要全域性唯一的id作為資料庫主鍵。如何生成全域性唯一id?首先,需要確定全域性唯一id是整型還是字串?如果是字串,那麼現有的uuid就完全滿足需求,不需要額外的工作。缺點是字串作為id占用空間大,索引效率比整型低。如果採用整型作為id,那麼首先排除掉32位int型別,因為範圍太小...

分布式唯一id生成器的想法

前端時間遇到乙個問題,怎麼快速生成唯一的id,後來採用了hashid的方法。最近在網上讀到了美團關於分布式唯一id生成器的解決方案,其中提到了三種生成法 建議看一下這篇文章,寫得很詳細,分析到位 文中提到了如下幾個問題 美團針對上面的場景,作了兩種方案,leaf segment 資料庫方式 和lea...