Skip to content

Commit 65f85f1

Browse files
committed
feat: add snowflake ID parser method
1 parent 5fd1e8e commit 65f85f1

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

backend/utils/snowflake.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,5 +102,26 @@ def generate(self) -> int:
102102
| self.sequence
103103
)
104104

105+
@staticmethod
106+
def parse_id(snowflake_id: int) -> dict:
107+
"""
108+
解析雪花ID,获取其包含的详细信息
109+
110+
:param snowflake_id: 雪花ID
111+
:return: 包含时间戳、集群ID、节点ID和序列号的字典
112+
"""
113+
timestamp = (snowflake_id >> SnowflakeConfig.TIMESTAMP_LEFT_SHIFT) + SnowflakeConfig.EPOCH
114+
cluster_id = (snowflake_id >> SnowflakeConfig.DATACENTER_ID_SHIFT) & SnowflakeConfig.MAX_DATACENTER_ID
115+
node_id = (snowflake_id >> SnowflakeConfig.WORKER_ID_SHIFT) & SnowflakeConfig.MAX_WORKER_ID
116+
sequence = snowflake_id & SnowflakeConfig.SEQUENCE_MASK
117+
118+
return {
119+
"timestamp": timestamp,
120+
"datetime": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(timestamp / 1000)),
121+
"cluster_id": cluster_id,
122+
"node_id": node_id,
123+
"sequence": sequence
124+
}
125+
105126

106127
snowflake = Snowflake()

0 commit comments

Comments
 (0)