forked from osgochina/donkeyid
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Donkeyid.php
107 lines (95 loc) · 2.76 KB
/
Donkeyid.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
<?php
/**
* Created by PhpStorm.
* User: ClownFish
* Email: 187231450#qq.com
* Date: 16-8-5
* Time: 下午2:14
*/
class Donkeyid
{
private $node_id;
private $epoch;
private $table;
const snowflake = 0;
const TIMESTAMP_BITS = 42;
const NODE_ID_BITS=12;
const SEQUENCE_BITS = 9;
const TIMESTAMP_LEFT_SHIFT = 21;
const NODE_ID_LEFT_SHIFT=9;
public function __construct($node_id=false,$epoch=false)
{
if ($node_id === false){
$node_id = ini_get("donkeyid.node_id");
}
if ($epoch === false){
$epoch = ini_get("donkeyid.epoch");
}
$this->node_id = ($node_id == false || $node_id < 0)?0:$node_id;
$this->epoch = ($epoch == false || $epoch < 0)?0:$epoch;
$this->create_table();
}
/**
* 创建共享内存
*/
private function create_table()
{
$this->table = new swoole_table(3);
$this->table->column("last_timestamp",swoole_table::TYPE_INT, 8);
$this->table->column("sequence",swoole_table::TYPE_INT, 4);
$this->table->create();
}
/**
* 获取当前毫秒
* @return int
*/
private function get_curr_timestamp_ms()
{
return (int)(microtime(true)*1000);
}
/**
* 暂停一毫秒
* @return int
*/
private function wait_next_ms()
{
usleep(1000);
return $this->get_curr_timestamp_ms();
}
/**
* 获取id
* @return int
*/
public function dk_get_next_id()
{
$now = $this->get_curr_timestamp_ms();
$this->table->lock();
$col = $this->table->get(self::snowflake);
if ($col == false || $col["last_timestamp"] > $now){
$last_timestamp = $now;
$sequence = rand(0,10) % 2;
}else{
$last_timestamp = $col["last_timestamp"];
$sequence = $col["sequence"];
}
if ($now == $last_timestamp){
$sequence = ($sequence+1)&((-1^(-1<<self::SEQUENCE_BITS)));
if ($sequence == 0){
$now = $this->wait_next_ms();
}
}
$this->table->set(self::snowflake,array("last_timestamp"=>$now,"sequence"=>$sequence));
$id = (($now-($this->epoch*1000)&(-1^(-1<<self::TIMESTAMP_BITS)))<<self::TIMESTAMP_LEFT_SHIFT)
|(($this->node_id&(-1^(-1<<self::NODE_ID_BITS)))<<self::NODE_ID_LEFT_SHIFT)
|($sequence);
$this->table->unlock();
return $id;
}
public function dk_parse_id($id)
{
$ret["time"] = ($id>>self::TIMESTAMP_LEFT_SHIFT)+($this->epoch*1000);
$ret["node_id"] = ($id>>self::NODE_ID_LEFT_SHIFT)&(-1^(-1<<self::NODE_ID_BITS));
$ret["sequence"] = $id&(-1^(-1<<self::SEQUENCE_BITS));
return $ret;
}
}