這篇文章主要介紹了關(guān)于雪花算法及運(yùn)用PHP,有著一定的參考價(jià)值,現(xiàn)在分享給大家,有需要的朋友可以參考一下
/** * 分布式 id 生成類(lèi) 組成: <毫秒級(jí)時(shí)間戳+機(jī)器id+序列號(hào)> * 默認(rèn)情況下41bit的時(shí)間戳可以支持該算法使用到2082年,10bit的工作機(jī)器id可以支持1023臺(tái)機(jī)器,序列號(hào)支持1毫秒產(chǎn)生4095個(gè)自增序列id * @author zhangqi */html' target='_blank'>class IdCreate{ const EPOCH = 1479533469598; //開(kāi)始時(shí)間,固定一個(gè)小于當(dāng)前時(shí)間的毫秒數(shù) const max12bit = 4095; const max41bit = 1099511627775; static $machineId = null; // 機(jī)器id public static function machineId($mId = 0) { self::$machineId = $mId; } public static function createOnlyId() { // 時(shí)間戳 42字節(jié) $time = floor(microtime(true) * 1000); // 當(dāng)前時(shí)間 與 開(kāi)始時(shí)間 差值 $time -= self::EPOCH; // 二進(jìn)制的 毫秒級(jí)時(shí)間戳 $base = decbin(self::max41bit + $time); // 機(jī)器id 10 字節(jié) if(!self::$machineId) { $machineid = self::$machineId; } else { $machineid = str_pad(decbin(self::$machineId), 10, "0", STR_PAD_LEFT); } // 序列數(shù) 12字節(jié) $random = str_pad(decbin(mt_rand(0, self::max12bit)), 12, "0", STR_PAD_LEFT); // 拼接 $base = $base.$machineid.$random; // 轉(zhuǎn)化為 十進(jìn)制 返回 return bindec($base); }運(yùn)用
$this->load->library('IdCreate'); $machineId = 1; $peopleData['id'] = $cast_id = IdCreate::createOnlyId($machineId);
相關(guān)推薦:
PHP的AES加密算法實(shí)例詳解
以上就是雪花算法及運(yùn)用PHP的詳細(xì)內(nèi)容,更多請(qǐng)關(guān)注 其它相關(guān)文章!
鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標(biāo)記有誤,請(qǐng)第一時(shí)間聯(lián)系我們修改或刪除,多謝。
新聞熱點(diǎn)
疑難解答
圖片精選