1
0
mirror of synced 2025-11-06 03:20:55 +08:00
Files
SnowFlake-IdGenerator/Python/README.md
2022-08-24 21:34:09 +08:00

44 lines
1.3 KiB
Markdown
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# ❄ idgenerator-Python
## 运行环境
Python 3.6+
## 引用 包
## 调用示例
调用方法如下其中worker_id为一个全局唯一的数字。
```python
# 导入包
from source import options, generator
# 声明id生成器参数需要自己构建一个worker_id
options = options.IdGeneratorOptions(worker_id=23)
# 参数中worker_id_bit_length 默认值6支持的 worker_id 最大值为2^6-1若 worker_id 超过64可设置更大的 worker_id_bit_length
idgen = generator.DefaultIdGenerator()
# 保存参数
idgen.set_id_generator(options)
# 生成id
uid = idgen.next_id()
# 打印出来查看
print("%d, %x" % (uid,uid))
```
包里面也提供了一个基于redis的worker id注册器使用方法如下
```python
from source import idregister
# 声明注册器提供redis地址
register = idregister.Register(host="127.0.0.1", port=6379, max_worker_id=100)
# 获取worker id
worker_id = register.get_worker_id()
# 打印出来查看
print(worker_id)
# 程序退出的时候调用一次stop
register.stop()
```
需要注意注册器会启动一个线程每隔一定时间向redis续期worker id可以在最后退出程序的时候调用一次stop函数使该线程退出不过这需要等待几秒钟。