From 619eda52f11b696626625dc830b56c3947ed6392 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=AD=E6=BD=87?= <1576730710@qq.com> Date: Wed, 5 Nov 2025 17:20:33 +0800 Subject: [PATCH] =?UTF-8?q?[python]=20=E5=A2=9E=E5=8A=A0=E6=97=B6=E9=97=B4?= =?UTF-8?q?=E7=AA=97=E5=8F=A3=E4=BF=9D=E6=8A=A4=EF=BC=8C=E9=81=BF=E5=85=8D?= =?UTF-8?q?=E4=B8=8E=E7=83=AD=E5=8A=A0=E8=BD=BD=E6=B3=A8=E5=86=8C=E5=86=B2?= =?UTF-8?q?=E7=AA=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../heart_beat_agent.py | 26 ++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/framework/fit/python/plugin/fit_py_heart_beat_agent/heart_beat_agent.py b/framework/fit/python/plugin/fit_py_heart_beat_agent/heart_beat_agent.py index 2fd79eb78..9a879089b 100644 --- a/framework/fit/python/plugin/fit_py_heart_beat_agent/heart_beat_agent.py +++ b/framework/fit/python/plugin/fit_py_heart_beat_agent/heart_beat_agent.py @@ -36,6 +36,8 @@ _LAST_HEART_BEAT_SUCCESS_TIME = time.time() # 心跳进程是否意外退出 _HEART_BEAT_EXIT_UNEXPECTEDLY = False +# 上次注册服务的时间,用于避免频繁注册覆盖热加载的服务 +_LAST_REGISTRY_TIME = 0 @value('heart-beat.client.sceneType', "fit-registry") @@ -83,7 +85,7 @@ def shutdown() -> None: def _try_heart_beat_once(): - global _FAIL_COUNT, _LAST_HEART_BEAT_SUCCESS_TIME + global _FAIL_COUNT, _LAST_HEART_BEAT_SUCCESS_TIME, _LAST_REGISTRY_TIME try: heartbeat([HeartBeatInfo(_scene_type(), _alive_time(), _init_delay())], HeartBeatAddress(get_runtime_worker_id())) @@ -93,11 +95,27 @@ def _try_heart_beat_once(): sys_plugin_logger.warning(f"heart beat unstable. " f"heart_beat_gap={'{:.3f}'.format(heart_beat_gap)}s, " f"heart_beat_interval={'{:.3f}'.format(_interval() / 1000)}s]") + + # 心跳重连成功后,需要重新注册所有服务,确保服务不丢失 + # 但为了避免覆盖热加载刚注册的服务,增加时间窗口保护(3倍心跳间隔) + current_time = time.time() + registry_protection_window = 3 * _interval() / 1000 # 保护窗口:3倍心跳间隔 + should_registry = False + if _FAIL_COUNT != 0: + # 重连成功,必须注册(解决服务丢失问题) + should_registry = True sys_plugin_logger.info(f"heart beat reconnect success. [fail_count={_FAIL_COUNT}]") _FAIL_COUNT = 0 - # 当前的优化仅为临时优化,待 Nacos 版注册中心上线后,更新并验证 - _registry_fitable_addresses() + elif _LAST_REGISTRY_TIME > 0 and current_time - _LAST_REGISTRY_TIME > registry_protection_window: + # 距离上次注册时间超过保护窗口,可以注册(用于兜底,防止服务丢失) + should_registry = True + + if should_registry: + # 当前的优化仅为临时优化,待 Nacos 版注册中心上线后,更新并验证 + _registry_fitable_addresses() + _LAST_REGISTRY_TIME = current_time + sys_plugin_logger.debug(f'heart beating success.') _LAST_HEART_BEAT_SUCCESS_TIME = heart_beat_finish_time except: @@ -168,8 +186,10 @@ def _registry_fitable_addresses(): """ Register with the registration center after the heartbeat is reconnected. """ + global _LAST_REGISTRY_TIME try: register_all_fit_services() + _LAST_REGISTRY_TIME = time.time() sys_plugin_logger.debug("In heart beat agent registry all fitable address success.") except: sys_plugin_logger.warning(f"In heart beat agent registry all fitable address failed.")