php idwork,idwork.php
/**
* ID 生成策略
* 毫秒級時間41位+機器ID 10位+毫秒內序列12位。
* 0 41 51 64
+-----------+------+------+
|time |pc |inc |
+-----------+------+------+
* 前41bits是以微秒為單位的timestamp。
* 接著10bits是事先配置好的機器ID。
* 最后12bits是累加計數器。
* macheine id(10bits)標明最多只能有1024臺機器同時產生ID,sequence number(12bits)也標明1臺機器1ms中最多產生4096個ID,
*
* auth: zhouyuan
*/
class idwork
{
const debug = 1;
static $workerId;
static $twepoch = 1361775855078;
static $sequence = 0;
const workerIdBits = 4;
static $maxWorkerId = 15;
const sequenceBits = 10;
static $workerIdShift = 10;
static $timestampLeftShift = 14;
static $sequenceMask = 1023;
private static $lastTimestamp = -1;
function __construct($params){
$workId = $params['workId'];
if($workId > self::$maxWorkerId || $workId< 0 )
{
throw new Exception("worker Id can't be greater than 15 or less than 0");
}
self::$workerId=$workId;
}
function timeGen(){
//獲得當前時間戳
$time = explode(' ', microtime());
$time2= substr($time[0], 2, 3);
return $time[1].$time2;
}
function tilNextMillis($lastTimestamp) {
$timestamp = $this->timeGen();
while ($timestamp <= $lastTimestamp) {
$timestamp = $this->timeGen();
}
return $timestamp;
}
function nextId()
{
$timestamp=$this->timeGen();
if(self::$lastTimestamp == $timestamp) {
self::$sequence = (self::$sequence + 1) & self::$sequenceMask;
if (self::$sequence == 0) {
$timestamp = $this->tilNextMillis(self::$lastTimestamp);
}
} else {
self::$sequence = 0;
}
if ($timestamp < self::$lastTimestamp) {
throw new Excwption("Clock moved backwards. Refusing to generate id for ".(self::$lastTimestamp-$timestamp)." milliseconds");
}
self::$lastTimestamp = $timestamp;
$nextId = ((sprintf('%.0f', $timestamp) - sprintf('%.0f', self::$twepoch) )<< self::$timestampLeftShift ) | ( self::$workerId << self::$workerIdShift ) | self::$sequence;
return $nextId;
}
}
?>
一鍵復制
編輯
Web IDE
原始數據
按行查看
歷史
總結
以上是生活随笔為你收集整理的php idwork,idwork.php的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: php中orm模型,模型model
- 下一篇: myeclipse启动php,myecl