125

dedid/README.chs.md at master · dekuan/dedid · GitHub

 6 years ago
source link: https://github.com/dekuan/dedid/blob/master/README.chs.md?
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

dekuan/dedid

一种为分布式数据库而设计的全局唯一 ID(主键)生成器。 本算法的实现参考了 Twitter Snowflake,但是在最后的 12 位您不仅仅可以使用随机数字,也可以通过指定字符串来获取哈希值。

结构体概况

本算法使用一个 64 位的 int 值作为 ID 的载体。

0 xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx x xxxxxx xxxxxx xx xxxxxxxx

结构体说明

位置 长度 用途 备注
0 1 保留位 一直都是 0
1~41 41 以毫秒为单位的流淌时间 0~69 年,即本 ID 算法最多可以使用 69 年
42~46 5 数据中心编号 编号范围 0~31,最多可容纳 32 个数据中心
47~51 5 数据中心下属数据节点编号 编号范围 0~31,每个数据中心最多可容纳 32 个数据节点。所以整个系统最多可容纳 1024 个数据节点
52~63 12 随机数/哈希值 取值范围 0~4095

数据中心编号

0 00000000 00000000 00000000 00000000 00000000 0 11111 00000 0000 00000000

00000000 00000000 00000000 00000000 00000000 00111110 00000000 00000000

00       00       00       00       00       3E       00       00

数据节点编号

0 00000000 00000000 00000000 00000000 00000000 0 00000 11111 0000 00000000

00000000 00000000 00000000 00000000 00000000 00000001 11110000 00000000

00       00       00       00       00       01       F0       00
0 11111111 11111111 11111111 11111111 11111111 1 00000 00000 0000 00000000

01111111 11111111 11111111 11111111 11111111 11000000 00000000 00000000

7F       FF       FF       FF       FF       C0       00       00

随机数/哈希值

0 00000000 00000000 00000000 00000000 00000000 0 00000 00000 1111 11111111

00000000 00000000 00000000 00000000 00000000 00000000 00001111 11111111

00       00       00       00       00       00       0F       FF

创建一个普通的随机数 ID

$cDId		= CDId::getInstance();
$nCenter	= 0;
$nNode		= 1;

$arrD		= [];
$nNewId	= $cDId->createId( $nCenter, $nNode, null, $arrD );

echo "new id = " . $nNewId . "\r\n";
print_r( $arrD );
new id = 114654484990270790
Array
(
    [center] => 0
    [node] => 1
    [time] => 27335759399
    [rand] => 3398
)

指定字符串,创建一个带有哈希值的 ID

$cDId		= CDId::getInstance();
$nCenter	= 0;
$nNode		= 15;

$sSrc		= "dekuan";
$arrD		= [];
$nNewId	= $cDId->createId( $nCenter, $nNode, $sSrc, $arrD );

echo "new id = " . $nNewId . "\r\n";
print_r( $arrD );
new id = 114654631304370386
Array
(
    [center] => 0
    [node] => 1
    [time] => 27335794283
    [rand] => 2258
)

解析 ID 获取详细信息

$cDId		= CDId::getInstance();
$arrId		= $cDId->parseId( 114654631304370386 );
print_r( $arrId );
Array
(
    [center] => 0
    [node] => 1
    [time] => 27335794283
    [rand] => 2258
)
# composer require dekuan/dedid

了解更多信息,敬请访问 https://packagist.org/packages/dekuan/dedid


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK