雪花算法原理
Snowflake是Twitter提出的一个算法,其目的是生成一个64位的整数:
0b100000010100001101000101011101010101010010000000001000000000001
1位:一般是符号位,不做处理
41位:用来记录时间戳(可以记录69年)
10位:前五位(机房编号/数据中心)后五位(机器编号)
12位:循环位(随机数),对于同一毫秒产生的不同id,12位最高可以记录4095个,也就是最多记录4095个,超过的需要的下一毫秒
雪花算法实现
https://gitee.com/yitter/idgenerator
PostgreSQL版本
CREATE SEQUENCE "public"."assign_id_seq"
INCREMENT 1
MINVALUE 1
MAXVALUE 99999999999999999
START 1
CACHE 1
CYCLE ;
ALTER SEQUENCE "public"."assign_id_seq" OWNER TO "postgres";
CREATE OR REPLACE FUNCTION "public"."snow_next_id"(OUT "result" int8)
RETURNS "pg_catalog"."int8" AS $BODY$
DECLARE
our_epoch bigint := 1314220021721;
seq_id bigint;
now_millis bigint;
shard_id int := 5;
BEGIN
seq_id := nextval('assign_id_seq') % 1024;
SELECT FLOOR(EXTRACT(EPOCH FROM clock_timestamp()) * 1000) INTO now_millis;
result := (now_millis - our_epoch) << 23;
result := result | (shard_id << 10);
result := result | (seq_id);
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION "public"."snow_next_id"(OUT "result" int8) OWNER TO "postgres";
SELECT snow_next_id();
CREATE TABLE "public"."temp2" (
"id" int8 NOT NULL DEFAULT snow_next_id(),
"name" varchar(255) COLLATE "pg_catalog"."default"
)
https://blog.csdn.net/qq_41982570/article/details/123925887
https://blog.csdn.net/weixin_40986713/article/details/126183243
- python版本
pip install pysnowflake
snowflake_start_server --worker=1 --dc=1 --port=30001
--address
:本机的IP地址默认localhost这里解释一下参数意思(可以通过--help来获取):--dc
:数据中心唯一标识符默认为0--worker
:工作者唯一标识符默认为0--log_file_prefix
:日志文件所在位置
import snowflake.client
snowflake.client.setup("127.0.0.1", 30001)
snowflake.client.get_guid()
snowflake.client.get_stats()
其他guid方案
--- 百度uid-generator:
https://gitee.com/mirrors/UidGenerator
https://github.com/baidu/uid-generator
https://blog.csdn.net/Jacksun_huang/article/details/99948429
--- Leaf—美团点评分布式ID生成系统:
https://tech.meituan.com/2019/03/07/open-source-project-leaf.html
https://tech.meituan.com/2017/04/21/mt-leaf.html
--- 雪花算法SpringBoot版
https://gitee.com/darkranger/id-generator
--- 推荐基于python实现:
https://www.cnblogs.com/oklizz/p/11865750.html
--- 其他:
https://www.jianshu.com/p/1271babe6b08
雪花算法python实现 https://www.cnblogs.com/oklizz/p/11865750.html
snowflake 分布式唯一ID生成器: https://www.cnblogs.com/galengao/p/5780519.html
Go版本snowflake: https://juejin.cn/post/6873458630516015111
py版本snowflake: https://pysnowflake.readthedocs.io/en/latest/
py版本snowflake: https://www.cnblogs.com/hellojesson/p/12942757.html