Snowflake algorithm and application of PHP

Source: Internet
Author: User

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);
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.