1 Star 0 Fork 1

lj2000hjy / snowflake

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
MIT

snowflake

Twitter雪花算法snowflake的PHP实现,解决并发可能造成id重复的问题

概述

  • snowflake算法生成的19个字符长度的唯一数字id
  • 由于php-fpm多进程的特性,并发下可能造成id重复,提供redis和文件锁两种方式来控制并发下的id重复,默认使用文件锁形式
  • 生成的id基于时间趋势增长
  • 支持生成时间到2080-09-05
  • 支持32个数据中心,32台机器
  • 每毫秒内可以生成4096个不同id

snowflake算法简述

使用64bit来标识一个唯一id,生成规则:

1bit正负标识位 - 41bits毫秒级时间戳 - 5bits数据中心id - 5bits机器id -12bits毫秒内顺序id

使用说明
引用包
composer require wantp/snowflake
生成id
require_once 'vendor/autoload.php';

$IdWorker = \wantp\Snowflake\IdWorker::getIns();
$id = $IdWorker->id();
反向解析id
$idInfo = $IdWorker->parse($id);
分布式,设置机器id
$dataCenterId = 2;
$machineId = 5;
$IdWorker = \wantp\Snowflake\IdWorker::getIns($dataCenterId,$machineId);
$id = $IdWorker->id();
使用redis来控制并发
  • 需要先安装配置好redis,设置redis时需要填写redis配置
  • redis配置说明
key 是否必填 说明
host redis主机
port redis端口
dbIndex redis db index
auth redis认证
$resdisConfig = ['host'=>'redis host','port'=>'redis port','dbIndex'=>'redis dbIndex',auth'=>'redis auth'];
$IdWorker = \wantp\Snowflake\IdWorker::getIns()->setRedisConutServer($resdisConfig);
$id = $IdWorker->id();
MIT License Copyright (c) 2018 zhang rongwang Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

简介

Twitter雪花算法snowflake的PHP实现,解决并发可能造成id重复的问题 展开 收起
PHP
MIT
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
PHP
1
https://gitee.com/lj2000hjy/snowflake-1.git
git@gitee.com:lj2000hjy/snowflake-1.git
lj2000hjy
snowflake-1
snowflake
master

搜索帮助