鱼哥哥

导航

PG雪花算法生成新ID

--序列

CREATE SEQUENCE table_id_seq increment by 1 maxvalue 999999999999999 minvalue 1 start 1 cycle;



--函数
create function snow_next_id(OUT result bigint) returns bigint
language plpgsql
as
$$
DECLARE
our_epoch bigint := 1483200000000;
seq_id bigint;
now_millis bigint;
shard_id int := 5;
BEGIN
seq_id := nextval('table_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;
$$;



--查询id
--generate_series(1,10)获取生成id数(1,10)为生成10个连续id
SELECT generate_series(1,10),SNOW_NEXT_ID() AS ID

posted on 2022-03-28 10:15  鱼哥哥  阅读(438)  评论(0编辑  收藏  举报