展开菜单
首页 精品内容 本月促销 装机必备 Windows PDF教程 macOS软件 IOS软件 Android AI 专题
全部分类

当前位置:

首页 > 编程开发 > 基于Python如何实现配置热加载

基于Python如何实现配置热加载

背景由于最近工作需求,需要在已有项目添加一个新功能,实现配置热加载的功能。所谓的配置热加载,也就是说当服务收到配置更新消息之后,我们不用重启服务就可以使用最新的配置去执行任务。如何实现下面我分别采用多进程、多线程、协程的方式去实现配置热加载。使用多进程实现配置热加载如果我们代码实现上使用多进程,主进程1来更新配置并发送指令,任务的调用是进程2,如何实现配置热加载呢?使用signal信号量来实现热加载当主进程收到配置更新的消息之后(配置读取是如何收到配置更新的消息的?这里我们暂不讨论),主进程就向进子程1发

本文目录

      背景

      由于最近工作需求,需要在已有项目添加一个新功能,实现配置热加载的功能。所谓的配置热加载,也就是说当服务收到配置更新消息之后,我们不用重启服务就可以使用最新的配置去执行任务。

      如何实现

      下面我分别采用多进程、多线程、协程的方式去实现配置热加载。

      使用多进程实现配置热加载

      如果我们代码实现上使用多进程, 主进程1来更新配置并发送指令,任务的调用是进程2,如何实现配置热加载呢?

      使用signal信号量来实现热加载

      基于Python如何实现配置热加载

      当主进程收到配置更新的消息之后(配置读取是如何收到配置更新的消息的? 这里我们暂不讨论), 主进程就向进子程1发送kill信号,子进程1收到kill的信号就退出,之后由信号处理函数来启动一个新的进程,使用最新的配置文件来继续执行任务。

      main 函数

      def main():
          # 启动一个进程执行任务
          p1 = Process(target=run, args=("p1",))
          p1.start()
      
          monitor(p1, run) # 注册信号
          processes["case100"] = p1 #将进程pid保存
          num = 0 
          while True: # 模拟获取配置更新
              print(
                  f"{multiprocessing.active_children()=}, count={len(multiprocessing.active_children())}\n")
              print(f"{processes=}\n")
              sleep(2)
              if num == 4:
                  kill_process(processes["case100"]) # kill 当前进程
              if num == 8:
                  kill_process(processes["case100"]) # kill 当前进程
              if num == 12:
                  kill_process(processes["case100"]) # kill 当前进程
              num += 1

      signal_handler 函数

      def signal_handler(process: Process, func, signum, frame):
          # print(f"{signum=}")
          global counts
      
          if signum == 17:  # 17 is SIGCHILD 
              # 这个循环是为了忽略SIGTERM发出的信号,避免抢占了主进程发出的SIGCHILD
              for signame in [SIGTERM, SIGCHLD, SIGQUIT]:
                  signal.signal(signame, SIG_DFL)
      
              print("Launch a new process")
              p = multiprocessing.Process(target=func, args=(f"p{counts}",))
              p.start()
              monitor(p, run)
              processes["case100"] = p
              counts += 1
      
          if signum == 2:
              if process.is_alive():
                  print(f"Kill {process} process")
                  process.terminate()
              signal.signal(SIGCHLD, SIG_IGN)
              sys.exit("kill parent process")

      完整代码如下

      #! /usr/local/bin/python3.8
      from multiprocessing import Process
      from typing import Dict
      import signal
      from signal import SIGCHLD, SIGTERM, SIGINT, SIGQUIT, SIG_DFL, SIG_IGN
      import multiprocessing
      from multiprocessing import Process
      from typing import Callable
      from data import processes
      import sys
      from functools import partial
      import time
      
      processes: Dict[str, Process] = {}
      counts = 2
      
      
      def run(process: Process):
          while True:
              print(f"{process} running...")
              time.sleep(1)
      
      
      def kill_process(process: Process):
          print(f"kill {process}")
          process.terminate()
      
      
      def monitor(process: Process, func: Callable):
          for signame in [SIGTERM, SIGCHLD, SIGINT, SIGQUIT]:
              # SIGTERM is kill signal.
              # No SIGCHILD is not trigger singnal_handler,
              # No SIGINT is not handler ctrl+c,
              # No SIGQUIT is RuntimeError: reentrant call inside <_io.BufferedWriter name=''>
              signal.signal(signame, partial(signal_handler, process, func))
      
      
      def signal_handler(process: Process, func, signum, frame):
          print(f"{signum=}")
          global counts
      
          if signum == 17:  # 17 is SIGTERM
              for signame in [SIGTERM, SIGCHLD, SIGQUIT]:
                  signal.signal(signame, SIG_DFL)
              print("Launch a new process")
              p = multiprocessing.Process(target=func, args=(f"p{counts}",))
              p.start()
              monitor(p, run)
              processes["case100"] = p
              counts += 1
      
          if signum == 2:
              if process.is_alive():
                  print(f"Kill {process} process")
                  process.terminate()
              signal.signal(SIGCHLD, SIG_IGN)
              sys.exit("kill parent process")
      
      
      def main():
          p1 = Process(target=run, args=("p1",))
          p1.start()
          monitor(p1, run)
          processes["case100"] = p1
          num = 0
          while True:
              print(
                  f"{multiprocessing.active_children()=}, count={len(multiprocessing.active_children())}\n")
              print(f"{processes=}\n")
              time.sleep(2)
              if num == 4:
                  kill_process(processes["case100"])
              if num == 8:
                  kill_process(processes["case100"])
              if num == 12:
                  kill_process(processes["case100"])
              num += 1
      
      
      if __name__ == '__main__':
          main()

      执行结果如下

      multiprocessing.active_children()=[], count=1
      
      processes={'case100': }
      
      p1 running...
      p1 running...
      kill 
      multiprocessing.active_children()=[], count=1
      
      processes={'case100': }
      
      signum=17
      Launch a new process
      p2 running...
      p2 running...
      multiprocessing.active_children()=[], count=1
      
      processes={'case100': }
      
      p2 running...
      p2 running...
      multiprocessing.active_children()=[], count=1
      
      processes={'case100': }
      
      p2 running...
      p2 running...
      multiprocessing.active_children()=[], count=1
      
      processes={'case100': }
      
      p2 running...
      p2 running...
      kill 
      signum=17
      Launch a new process
      multiprocessing.active_children()=[], count=1
      
      processes={'case100': }
      
      p3 running...
      p3 running...
      multiprocessing.active_children()=[], count=1

      总结

      好处:使用信号量可以处理多进程之间通信的问题。

      坏处:代码不好写,写出来代码不好理解。信号量使用必须要很熟悉,不然很容易自己给自己写了一个bug.(所有初学者慎用,老司机除外。)

      还有一点不是特别理解的就是process.terminate() 发送出信号是SIGTERM number是15,但是第一次signal_handler收到信号却是number=17,如果我要去处理15的信号,就会导致前一个进程不能kill掉的问题。欢迎有对信号量比较熟悉的大佬,前来指点迷津,不甚感谢。

      采用multiprocessing.Event 来实现配置热加载

      实现逻辑是主进程1 更新配置并发送指令。进程2启动调度任务。

      这时候当主进程1更新好配置之后,发送指令给进程2,这时候的指令就是用Event一个异步事件通知。

      直接上代码

      scheduler 函数

      def scheduler():
          while True:
              print('wait message...')
              case_configurations = scheduler_notify_queue.get()
              print(f"Got case configurations {case_configurations=}...")
      
              task_schedule_event.set() # 设置set之后, is_set 为True
      
              print(f"Schedule will start ...")
              while task_schedule_event.is_set(): # is_set 为True的话,那么任务就会一直执行
                  run(case_configurations)
      
              print("Clearing all scheduling job ...")

      event_scheduler 函数

      def event_scheduler(case_config):
      
          scheduler_notify_queue.put(case_config)
          print(f"Put cases config to the Queue ...")
      
          task_schedule_event.clear() # clear之后,is_set 为False
          print(f"Clear scheduler jobs ...")
      
          print(f"Schedule job ...")

      完整代码如下

      import multiprocessing
      import time
      
      
      scheduler_notify_queue = multiprocessing.Queue()
      task_schedule_event = multiprocessing.Event()
      
      
      def run(case_configurations: str):
          print(f'{case_configurations} running...')
          time.sleep(3)
      
      
      def scheduler():
          while True:
              print('wait message...')
              case_configurations = scheduler_notify_queue.get()
      
              print(f"Got case configurations {case_configurations=}...")
              task_schedule_event.set()
      
              print(f"Schedule will start ...")
              while task_schedule_event.is_set():
                  run(case_configurations)
      
              print("Clearing all scheduling job ...")
      
      
      def event_scheduler(case_config: str):
      
          scheduler_notify_queue.put(case_config)
          print(f"Put cases config to the Queue ...")
      
          task_schedule_event.clear()
          print(f"Clear scheduler jobs ...")
      
          print(f"Schedule job ...")
      
      
      def main():
          scheduler_notify_queue.put('1')
          p = multiprocessing.Process(target=scheduler)
          p.start()
      
          count = 1
          print(f'{count=}')
          while True:
              if count == 5:
                  event_scheduler('100')
              if count == 10:
                  event_scheduler('200')
              count += 1
              time.sleep(1)
      
      
      if __name__ == '__main__':
          main()

      执行结果如下

      wait message...
      Got case configurations case_configurations='1'...
      Schedule will start ...
      1 running...
      1 running...
      Put cases config to the Queue ...
      Clear scheduler jobs ...
      Schedule job ...
      Clearing all scheduling job ...
      wait message...
      Got case configurations case_configurations='100'...
      Schedule will start ...
      100 running...
      Put cases config to the Queue ...
      Clear scheduler jobs ...
      Schedule job ...
      Clearing all scheduling job ...
      wait message...
      Got case configurations case_configurations='200'...
      Schedule will start ...
      200 running...
      200 running...

      总结

      使用Event事件通知,代码不易出错,代码编写少,易读。相比之前信号量的方法,推荐大家多使用这种方式。

      使用多线程或协程的方式,其实和上述实现方式一致。唯一区别就是调用了不同库中,queue和 event.

      # threading
      scheduler_notify_queue = queue.Queue()
      task_schedule_event = threading.Event()
      
      # async
      scheduler_notify_queue = asyncio.Queue()
      task_schedule_event = asyncio.Event()
      本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系bd@zhengruan.com
      作者最新文章
      编程开发 Python
      相关文章 更多
      精品专题 更多
      装机必备

      正软商城装机必备专区,精选办公、浏览器、安全防护、影音播放、压缩解压、设计创作和系统工具等电脑常用正版软件,帮助用户快速完成新电脑软件配置。

      Windows

      正软商城Windows软件专区,汇集适用于Windows电脑的办公、设计、安全防护、影音播放、开发工具和系统优化软件,提供软件介绍、系统要求、正版授权及购买下载服务。

      PDF教程

      正软商城PDF教程频道提供PDF编辑、转换、合并、拆分、压缩及格式处理方法,同时介绍常用PDF软件和工具的使用技巧。

      macOS软件

      正软商城macOS软件专区,精选适用于Mac电脑的办公、设计、影音、效率、开发和系统工具,提供软件功能介绍、macOS兼容版本、正版授权及购买下载服务。

      IOS软件

      正软商城iOS软件专区,精选适用于iPhone和iPad的办公、学习、影音、设计、效率及AI应用,提供功能介绍、适用设备、系统要求和正版获取方式等信息。

      AI

      正软商城AI软件专区,汇集AI写作、AI绘画、AI视频、AI办公、AI编程、AI翻译、智能客服和数据分析等人工智能工具,提供功能介绍、适用平台、收费方式及正版购买信息。

      Mac软件 更多
      Aperty macOS版
      Aperty macOS版

      Aperty 是 Skylum 推出的 AI 人像修图软件,支持自然肤质修饰、瑕疵处理、面部与身体调整、预设及批量同步。

      火山引擎 网页版
      火山引擎 网页版

      火山引擎是字节跳动旗下企业级云与AI服务平台。聚焦大模型核心能力,依托字节自研豆包多模态大模型,凭借火山方舟一站式平台,提供模型精调、推理部署、智能应用搭建等全链路服务,结合高性能AI算力,助力各行业快速落地大模型数字化与智能化应用。

      立刻MV 网页版
      立刻MV 网页版

      立刻MV 面向音乐人、内容创作者和品牌团队,帮助用户低成本完成歌曲 MV、歌词视频、AI 分镜、图生视频与最终合成。

      蛙蛙写作 网页版
      蛙蛙写作 网页版

      蛙蛙写作 AI 创作工具,覆盖小说、剧本、文案,一键生成文稿,打通文字转视频全流程,高效解决创作难题。

      讯飞智作 网页版
      讯飞智作 网页版

      讯飞智作是一款基于语音合成技术、虚拟人驱动技术与数字人形象声音构建能力的 AI 数字人音视频创作平台。

      超级简历WonderCV 网页版
      超级简历WonderCV 网页版

      超级简历WonderCV是面向应届生和AI小白的智能求职平台,覆盖简历、面试与职业规划。

      音述AI 网页版
      音述AI 网页版

      音述AI,是一个以“用声音述说故事”为核心的 AI 音乐创作与声音分享社区。

      AionClaw macOS版
      AionClaw macOS版

      AionClaw 是可在桌面端运行的任务型 AI 助手,通过数字专家与技能市场组合办公、创作、数据和开发能力。

      Loomy macOS版
      Loomy macOS版

      Loomy 是科大讯飞推出的桌面 AI 助手,可通过对话、任务与工作目录协助处理办公、内容创作和资料整理。

      AirBuddy 3 macOS版
      AirBuddy 3 macOS版

      AirBuddy 3 是面向 macOS 的蓝牙外设增强工具,可集中查看 AirPods、Beats 与苹果设备电量,提供快速连接、播放控制、电量提醒、桌面小组件和多台 Mac 外设接力等功能。

      AirServer macOS版
      AirServer macOS版

      AirServer macOS版可把 Mac 转换为无线投屏接收端,通过 AirPlay 或 Google Cast 接收手机、平板和电脑画面,并支持多设备同时连接、高清镜像及会话录制,适合家庭娱乐、课堂教学、会议演示和应用展示。

      AnyDesk macOS版
      AnyDesk macOS版

      AnyDesk macOS版是一款适用于远程办公、设备维护和客户支持的远程桌面工具,可连接并操作异地计算机,支持文件传输、无人值守访问、会话权限控制及跨平台协作。

      WINDOWS 更多
      讯飞绘文 网页版
      讯飞绘文 网页版

      讯飞绘文网页版是科大讯飞推出的AI图文创作与内容运营工具,覆盖热点选题、文章生成、稿件校对、智能配图、排版发布和数据复盘等环节,适合自媒体创作者及内容团队在线使用。

      Maya(Autodesk Maya) Windows版
      Maya(Autodesk Maya) Windows版

      Autodesk Maya 是面向影视、电视、动画和游戏行业的专业三维制作软件,集多边形与 NURBS 建模、角色绑定、关键帧和动作捕捉动画、Bifrost 特效模拟、材质开发及 Arnold 渲染于一体,

      Aperty Windows版
      Aperty Windows版

      Aperty 是 Skylum 推出的 AI 人像修图软件,支持自然肤质修饰、瑕疵处理、面部与身体调整、预设及批量同步。

      火山引擎 网页版
      火山引擎 网页版

      火山引擎是字节跳动旗下企业级云与AI服务平台。聚焦大模型核心能力,依托字节自研豆包多模态大模型,凭借火山方舟一站式平台,提供模型精调、推理部署、智能应用搭建等全链路服务,结合高性能AI算力,助力各行业快速落地大模型数字化与智能化应用。

      立刻MV 网页版
      立刻MV 网页版

      立刻MV 面向音乐人、内容创作者和品牌团队,帮助用户低成本完成歌曲 MV、歌词视频、AI 分镜、图生视频与最终合成。

      蛙蛙写作 网页版
      蛙蛙写作 网页版

      蛙蛙写作 AI 创作工具,覆盖小说、剧本、文案,一键生成文稿,打通文字转视频全流程,高效解决创作难题。

      讯飞智作 网页版
      讯飞智作 网页版

      讯飞智作是一款基于语音合成技术、虚拟人驱动技术与数字人形象声音构建能力的 AI 数字人音视频创作平台。

      超级简历WonderCV 网页版
      超级简历WonderCV 网页版

      超级简历WonderCV是面向应届生和AI小白的智能求职平台,覆盖简历、面试与职业规划。

      音述AI 网页版
      音述AI 网页版

      音述AI,是一个以“用声音述说故事”为核心的 AI 音乐创作与声音分享社区。

      AionClaw Windows版
      AionClaw Windows版

      AionClaw 是可在桌面端运行的任务型 AI 助手,通过数字专家与技能市场组合办公、创作、数据和开发能力。

      Loomy Windows版
      Loomy Windows版

      Loomy 是科大讯飞推出的桌面 AI 助手,可通过对话、任务与工作目录协助处理办公、内容创作和资料整理。

      AirServer Windows版
      AirServer Windows版

      AirServer Windows版可把电脑变成AirPlay、Google Cast和Miracast无线投屏接收端,适合会议演示、课堂教学及家庭大屏分享。发送设备通常无需另装客户端,并可同时接收和智能排列多个镜像会话。