项目作者: dekuan

项目描述 :
An unique id generator for primary key of distributed database
高级语言: PHP
项目地址: git://github.com/dekuan/dedid.git
创建时间: 2017-08-03T18:09:33Z
项目社区:https://github.com/dekuan/dedid

开源协议:Apache License 2.0

下载


dekuan/dedid

An unique id generator for primary key of distributed database.
This implementation of the algorithm was referenced by Twitter Snowflake,
but in the last 12 bits you can not only use the random numbers, but also get a hash value by your specified string.

ALGORITHM

Bit structure

It’s a 64 bits bigint.

  1. 0 xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx x xxxxx xxxxx xxxx xxxxxxxx

Details

Position Length Usage Remark
0 1 Reserved Always be 0
1~41 41 Escaped Time (in millisecond) 0~69 years
42~46 5 Number of data center 0~31
47~51 5 Number of data node in the data center 0~31
52~63 12 Random / Hash 0~4095

Bit marks

Center

  1. 0 00000000 00000000 00000000 00000000 00000000 0 11111 00000 0000 00000000
  2. 00000000 00000000 00000000 00000000 00000000 00111110 00000000 00000000
  3. 00 00 00 00 00 3E 00 00

Node

  1. 0 00000000 00000000 00000000 00000000 00000000 0 00000 11111 0000 00000000
  2. 00000000 00000000 00000000 00000000 00000000 00000001 11110000 00000000
  3. 00 00 00 00 00 01 F0 00

Escaped Time

  1. 0 11111111 11111111 11111111 11111111 11111111 1 00000 00000 0000 00000000
  2. 01111111 11111111 11111111 11111111 11111111 11000000 00000000 00000000
  3. 7F FF FF FF FF C0 00 00

Random or Hash value

  1. 0 00000000 00000000 00000000 00000000 00000000 0 00000 00000 1111 11111111
  2. 00000000 00000000 00000000 00000000 00000000 00000000 00001111 11111111
  3. 00 00 00 00 00 00 0F FF

HOW TO USE

Create an new id normally

  1. $cDId = CDId::getInstance();
  2. $nCenter = 0;
  3. $nNode = 1;
  4. $arrD = [];
  5. $nNewId = $cDId->createId( $nCenter, $nNode, null, $arrD );
  6. echo "new id = " . $nNewId . "\r\n";
  7. print_r( $arrD );
output
  1. new id = 114654484990270790
  2. Array
  3. (
  4. [center] => 0
  5. [node] => 1
  6. [time] => 27335759399
  7. [rand] => 3398
  8. )

Create an new id with crc32 hash value by a specified string

  1. $cDId = CDId::getInstance();
  2. $nCenter = 0;
  3. $nNode = 15;
  4. $sSrc = "dekuan";
  5. $arrD = [];
  6. $nNewId = $cDId->createId( $nCenter, $nNode, $sSrc, $arrD );
  7. echo "new id = " . $nNewId . "\r\n";
  8. print_r( $arrD );
output
  1. new id = 114654631304370386
  2. Array
  3. (
  4. [center] => 0
  5. [node] => 1
  6. [time] => 27335794283
  7. [rand] => 2258
  8. )

Parse an id for getting the details

  1. $cDId = CDId::getInstance();
  2. $arrId = $cDId->parseId( 114654631304370386 );
  3. print_r( $arrId );
output
  1. Array
  2. (
  3. [center] => 0
  4. [node] => 1
  5. [time] => 27335794283
  6. [rand] => 2258
  7. )

INSTALL

  1. # composer require dekuan/dedid

For more information, please visit https://packagist.org/packages/dekuan/dedid