This article mainly introduces the snowflake algorithm and the use of PHP, has a certain reference value, now share to everyone, there is a need for friends can refer to the
/** * Distributed ID Generation class composition: < millisecond timestamp + machine id+ serial number > * By default 41bit timestamp can support the algorithm by 2082, 10bit working machine ID can support 1023 machines, serial number support 1 milliseconds to generate 4,095 Self-increment sequence ID * @author zhangqi */class idcreate{const EPOCH = 1479533469598; Start time, fixed a number of milliseconds less than the current time const MAX12BIT = 4095; Const MAX41BIT = 1099511627775; static $machineId = null; Machine ID public static function machineid ($mId = 0) {self:: $machineId = $mId; public static function Createonlyid () {//timestamp 42 bytes $time = Floor (Microtime (TRUE) * 1000); Current time and start difference $time-= Self::epoch; The millisecond timestamp of the binary $base = Decbin (self::max41bit + $time); Machine ID 10 byte if (!self:: $machineId) {$machineid = self:: $machineId; } else {$machineid = Str_pad (Decbin (self:: $machineId), and "0", str_pad_left); }//Sequence number 12 bytes $random = Str_pad (Decbin (Mt_rand (0, Self::max12bit)), "0", str_pad_left); Stitching $base = $base. $machineid. $random; Convert to Decimal returns return Bindec ($base); }
Use
$this->load->library (' idcreate '); $machineId = 1; $peopleData [' id '] = $cast _id = Idcreate::createonlyid ($machineId);