本文给大家聊聊雪花算法的php实现,希望对需要的朋友有所帮助!
雪花算法的实现
最近看了下雪花算法,自己试着写了一下
<?phpclass snowflake{ const twepoch = 0; // 时间起始标记点,作为基准,一般取系统的最近时间(一旦确定不能变动) const worker_id_bits = 5; // 机器标识位数 const datacenter_id_bits = 5; // 数据中心标识位数 const sequence_bits = 12; // 毫秒内自增位 private $workerid; // 工作机器id private $datacenterid; // 数据中心id private $sequence; // 毫秒内序列 private $maxworkerid = -1 ^ (-1 << self::worker_id_bits); // 机器id最大值 private $maxdatacenterid = -1 ^ (-1 << self::datacenter_id_bits); // 数据中心id最大值 private $workeridshift = self::sequence_bits; // 机器id偏左移位数 private $datacenteridshift = self::sequence_bits + self::worker_id_bits; // 数据中心id左移位数 private $timestampleftshift = self::sequence_bits + self::worker_id_bits + self::datacenter_id_bits; // 时间毫秒左移位数 private $sequencemask = -1 ^ (-1 << self::sequence_bits); // 生成序列的掩码 private $lasttimestamp = -1; // 上次生产id时间戳 public function __construct($workerid, $datacenterid, $sequence = 0) { if ($workerid > $this->maxworkerid || $workerid < 0) { throw new exception("worker id can't be greater than {$this->maxworkerid} or less than 0"); } if ($datacenterid > $this->maxdatacenterid || $datacenterid < 0) { throw new exception("datacenter id can't be greater than {$this->maxdatacenterid} or less than 0"); } $this->workerid = $workerid; $this->datacenterid = $datacenterid; $this->sequence = $sequence; } public function createid() { $timestamp = $this->createtimestamp(); if ($timestamp < $this->lasttimestamp) {//当产生的时间戳小于上次的生成的时间戳时,报错 $difftimestamp = bcsub($this->lasttimestamp, $timestamp); throw new exception("clock moved backwards. refusing to generate id for {$difftimestamp} milliseconds"); } if ($this->lasttimestamp == $timestamp) {//当生成的时间戳等于上次生成的时间戳的时候 $this->sequence = ($this->sequence + 1) & $this->sequencemask;//序列自增一次 if (0 == $this->sequence) {//当序列为0时,重新生成最新的时间戳 $timestamp = $this->createnexttimestamp($this->lasttimestamp); } } else {//当生成的时间戳不等于上次的生成的时间戳的时候,序列归0 $this->sequence = 0; } $this->lasttimestamp = $timestamp; return (($timestamp - self::twepoch) << $this->timestampleftshift) | ($this->datacenterid << $this->datacenteridshift) | ($this->workerid << $this->workeridshift) | $this->sequence; } protected function createnexttimestamp($lasttimestamp) //生成一个大于等于 上次生成的时间戳 的时间戳 { $timestamp = $this->createtimestamp(); while ($timestamp <= $lasttimestamp) { $timestamp = $this->createtimestamp(); } return $timestamp; } protected function createtimestamp()//生成毫秒级别的时间戳 { return floor(microtime(true) * 1000); }}?>
推荐学习:《php视频教程》
以上就是用php捣鼓一个雪花算法的详细内容。