【python雪花ID服务部署与调用】

安装

python3.8.15
pip3.8 install pysnowflake==0.1.3

配置-settings.py

#雪花算法生成ID服务端
SNOWFLAKE_SERVER = dict(
    host = "127.0.0.1",
    port = 8910,
    debug = False,
)

服务端-snowflake_service.py

#-*- coding:utf-8 -*-
import os
import sys
import settings
import signal
import subprocess
import shlex

def termination_signal_handler(signum, frame):
    print ('catched terminate singal: %d' % signum)
    globals_child.kill()
    sys.exit()

if __name__ == "__main__":
    signal.signal(signal.SIGTERM, termination_signal_handler)   #kill pid
    signal.signal(signal.SIGINT, termination_signal_handler)     #ctrl -c
    #signal.signal(signal.SIGKILL, term_sig_handler)  #kill -9 pid  此功能无效

    server_file_path = "snowflake_start_server"
    if os.name == "posix":
        server_file_path = "/usr/local/python38/bin/snowflake_start_server"

    command = "{server_file_path} --address={host} --dc=0 --debug={debug}  --port={port} --worker=0".format(
        server_file_path = server_file_path,
        host = settings.SNOWFLAKE_SERVER["host"],
        debug = settings.SNOWFLAKE_SERVER["debug"],
        port = settings.SNOWFLAKE_SERVER["port"],
    )

    print(command)

    args = shlex.split(command)

    global globals_child

    globals_child = subprocess.Popen(args)

    globals_child.wait()

客户端函数

import snowflake.client
def getSnowflakeId():
    global  globals_is_setup
    if not globals_is_setup:
        snowflake.client.setup(settings.SNOWFLAKE_SERVER["host"],settings.SNOWFLAKE_SERVER["port"])
        globals_is_setup = True

    return snowflake.client.get_guid()

supervisord部署

[program:snowflake_service]
directory=/data/xxx/xxx
command=python3 snowflake_service.py
autostart = true
startsecs = 5
user=sy
redirect_stderr = true
stdout_logfile_maxbytes = 20MB
stdout_logfile_backups = 20
stdout_logfile =/data/logs/xxx/snowflake_service.log
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值