-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathIdGenerator.php
66 lines (54 loc) · 1.24 KB
/
IdGenerator.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
<?php
/**
* Created by PhpStorm.
* User: qinming
* Date: 2019/5/9
* Time: 下午12:16
*/
namespace App\Helpers;
use Illuminate\Support\Facades\Redis;
class IdGenerator
{
const TIMESTAMP_SHITF = 16;
const WORKER_SHITF = 12;
protected $workerId;
public function __construct($workerId = 1)
{
$this->workerId = $workerId;
}
protected function timestamp()
{
return round(microtime(true) * 1000);
}
public function next()
{
$timestamp = $this->timestamp();
return ($timestamp << self::TIMESTAMP_SHITF)
| ($this->getWorkerId() << self::SEED_SHITF)
| $this->getCount($timestamp);
}
/**
* 4bit for seed, 可用于业务和环境区分
* @return int
*/
public function getWorkerId()
{
return $this->workerId;
}
/**
* 12bit for counter ,max 4096
* @param $timestamp
* @return int
*/
public function getCount($timestamp)
{
$n = Redis::incr($timestamp) + 1;
if ($n > 4096) { //2^12
usleep(200);
$timestamp = $this->timestamp();
$n = Redis::incr($timestamp) + 1;
Redis::expire($timestamp, 2);
}
return $n;
}
}