3636_LAST_HEART_BEAT_SUCCESS_TIME = time .time ()
3737# 心跳进程是否意外退出
3838_HEART_BEAT_EXIT_UNEXPECTEDLY = False
39+ # 上次注册服务的时间,用于避免频繁注册覆盖热加载的服务
40+ _LAST_REGISTRY_TIME = 0
3941
4042
4143@value ('heart-beat.client.sceneType' , "fit-registry" )
@@ -83,7 +85,7 @@ def shutdown() -> None:
8385
8486
8587def _try_heart_beat_once ():
86- global _FAIL_COUNT , _LAST_HEART_BEAT_SUCCESS_TIME
88+ global _FAIL_COUNT , _LAST_HEART_BEAT_SUCCESS_TIME , _LAST_REGISTRY_TIME
8789 try :
8890 heartbeat ([HeartBeatInfo (_scene_type (), _alive_time (), _init_delay ())],
8991 HeartBeatAddress (get_runtime_worker_id ()))
@@ -93,11 +95,27 @@ def _try_heart_beat_once():
9395 sys_plugin_logger .warning (f"heart beat unstable. "
9496 f"heart_beat_gap={ '{:.3f}' .format (heart_beat_gap )} s, "
9597 f"heart_beat_interval={ '{:.3f}' .format (_interval () / 1000 )} s]" )
98+
99+ # 心跳重连成功后,需要重新注册所有服务,确保服务不丢失
100+ # 但为了避免覆盖热加载刚注册的服务,增加时间窗口保护(3倍心跳间隔)
101+ current_time = time .time ()
102+ registry_protection_window = 3 * _interval () / 1000 # 保护窗口:3倍心跳间隔
103+ should_registry = False
104+
96105 if _FAIL_COUNT != 0 :
106+ # 重连成功,必须注册(解决服务丢失问题)
107+ should_registry = True
97108 sys_plugin_logger .info (f"heart beat reconnect success. [fail_count={ _FAIL_COUNT } ]" )
98109 _FAIL_COUNT = 0
99- # 当前的优化仅为临时优化,待 Nacos 版注册中心上线后,更新并验证
100- _registry_fitable_addresses ()
110+ elif _LAST_REGISTRY_TIME > 0 and current_time - _LAST_REGISTRY_TIME > registry_protection_window :
111+ # 距离上次注册时间超过保护窗口,可以注册(用于兜底,防止服务丢失)
112+ should_registry = True
113+
114+ if should_registry :
115+ # 当前的优化仅为临时优化,待 Nacos 版注册中心上线后,更新并验证
116+ _registry_fitable_addresses ()
117+ _LAST_REGISTRY_TIME = current_time
118+
101119 sys_plugin_logger .debug (f'heart beating success.' )
102120 _LAST_HEART_BEAT_SUCCESS_TIME = heart_beat_finish_time
103121 except :
@@ -168,8 +186,10 @@ def _registry_fitable_addresses():
168186 """
169187 Register with the registration center after the heartbeat is reconnected.
170188 """
189+ global _LAST_REGISTRY_TIME
171190 try :
172191 register_all_fit_services ()
192+ _LAST_REGISTRY_TIME = time .time ()
173193 sys_plugin_logger .debug ("In heart beat agent registry all fitable address success." )
174194 except :
175195 sys_plugin_logger .warning (f"In heart beat agent registry all fitable address failed." )
0 commit comments