sycommon-python-lib 0.1.46__py3-none-any.whl → 0.1.56b5__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- sycommon/config/Config.py +6 -2
- sycommon/config/RerankerConfig.py +1 -0
- sycommon/database/async_base_db_service.py +36 -0
- sycommon/database/async_database_service.py +96 -0
- sycommon/llm/__init__.py +0 -0
- sycommon/llm/embedding.py +149 -0
- sycommon/llm/get_llm.py +246 -0
- sycommon/llm/llm_logger.py +126 -0
- sycommon/llm/llm_tokens.py +119 -0
- sycommon/logging/async_sql_logger.py +65 -0
- sycommon/logging/kafka_log.py +21 -9
- sycommon/logging/logger_levels.py +23 -0
- sycommon/middleware/context.py +2 -0
- sycommon/middleware/traceid.py +155 -32
- sycommon/notice/__init__.py +0 -0
- sycommon/notice/uvicorn_monitor.py +195 -0
- sycommon/rabbitmq/rabbitmq_client.py +144 -152
- sycommon/rabbitmq/rabbitmq_pool.py +213 -479
- sycommon/rabbitmq/rabbitmq_service.py +77 -127
- sycommon/services.py +78 -75
- sycommon/synacos/feign.py +18 -7
- sycommon/synacos/feign_client.py +26 -8
- sycommon/synacos/nacos_service.py +18 -2
- sycommon/tools/merge_headers.py +97 -0
- sycommon/tools/snowflake.py +290 -23
- {sycommon_python_lib-0.1.46.dist-info → sycommon_python_lib-0.1.56b5.dist-info}/METADATA +15 -10
- {sycommon_python_lib-0.1.46.dist-info → sycommon_python_lib-0.1.56b5.dist-info}/RECORD +30 -18
- {sycommon_python_lib-0.1.46.dist-info → sycommon_python_lib-0.1.56b5.dist-info}/WHEEL +0 -0
- {sycommon_python_lib-0.1.46.dist-info → sycommon_python_lib-0.1.56b5.dist-info}/entry_points.txt +0 -0
- {sycommon_python_lib-0.1.46.dist-info → sycommon_python_lib-0.1.56b5.dist-info}/top_level.txt +0 -0
|
@@ -15,7 +15,6 @@ from sycommon.rabbitmq.rabbitmq_pool import RabbitMQConnectionPool
|
|
|
15
15
|
from sycommon.logging.kafka_log import SYLogger
|
|
16
16
|
from sycommon.models.mqmsg_model import MQMsgModel
|
|
17
17
|
|
|
18
|
-
|
|
19
18
|
logger = SYLogger
|
|
20
19
|
|
|
21
20
|
|
|
@@ -23,8 +22,8 @@ class RabbitMQClient:
|
|
|
23
22
|
"""
|
|
24
23
|
RabbitMQ 客户端(支持消息发布、消费、自动重连、异常重试)
|
|
25
24
|
核心特性:
|
|
26
|
-
1.
|
|
27
|
-
2.
|
|
25
|
+
1. 基于单通道连接池复用资源,性能优化
|
|
26
|
+
2. 依赖连接池原生自动重连,客户端仅重建自身资源
|
|
28
27
|
3. 消息发布支持重试+mandatory机制+超时控制,确保路由有效
|
|
29
28
|
4. 消费支持手动ACK/NACK
|
|
30
29
|
5. 兼容JSON/字符串/字典消息格式
|
|
@@ -41,7 +40,6 @@ class RabbitMQClient:
|
|
|
41
40
|
auto_delete: bool = False,
|
|
42
41
|
auto_parse_json: bool = True,
|
|
43
42
|
create_if_not_exists: bool = True,
|
|
44
|
-
prefetch_count: int = 2,
|
|
45
43
|
**kwargs,
|
|
46
44
|
):
|
|
47
45
|
# 依赖注入:连接池(必须已初始化)
|
|
@@ -54,8 +52,8 @@ class RabbitMQClient:
|
|
|
54
52
|
try:
|
|
55
53
|
self.exchange_type = ExchangeType(exchange_type.lower())
|
|
56
54
|
except ValueError:
|
|
57
|
-
|
|
58
|
-
self.exchange_type = ExchangeType.
|
|
55
|
+
logger.warning(f"无效的exchange_type: {exchange_type},默认使用'topic'")
|
|
56
|
+
self.exchange_type = ExchangeType.TOPIC
|
|
59
57
|
|
|
60
58
|
# 队列配置
|
|
61
59
|
self.queue_name = queue_name.strip() if queue_name else None
|
|
@@ -65,9 +63,6 @@ class RabbitMQClient:
|
|
|
65
63
|
self.auto_parse_json = auto_parse_json # 自动解析JSON消息体
|
|
66
64
|
self.create_if_not_exists = create_if_not_exists # 不存在则创建交换机/队列
|
|
67
65
|
|
|
68
|
-
# 消费配置
|
|
69
|
-
self.prefetch_count = max(1, prefetch_count) # 每次预取消息数(避免消息堆积)
|
|
70
|
-
|
|
71
66
|
# 内部状态(资源+连接)
|
|
72
67
|
self._channel: Optional[Channel] = None
|
|
73
68
|
self._channel_conn: Optional[AbstractRobustConnection] = None # 通道所属连接
|
|
@@ -83,12 +78,10 @@ class RabbitMQClient:
|
|
|
83
78
|
self._connect_lock = asyncio.Lock()
|
|
84
79
|
# 跟踪连接关闭回调(用于后续移除)
|
|
85
80
|
self._conn_close_callback: Optional[Callable] = None
|
|
86
|
-
#
|
|
81
|
+
# 控制重连频率的信号量(限制并发重连数)
|
|
87
82
|
self._reconnect_semaphore = asyncio.Semaphore(1)
|
|
88
83
|
# 固定重连间隔15秒(全局统一)
|
|
89
84
|
self._RECONNECT_INTERVAL = 15
|
|
90
|
-
# 重连任务锁(确保同一时间只有一个重连任务)
|
|
91
|
-
self._reconnect_task_lock = asyncio.Lock()
|
|
92
85
|
# 跟踪当前重连任务(避免重复创建)
|
|
93
86
|
self._current_reconnect_task: Optional[asyncio.Task] = None
|
|
94
87
|
# 连接失败计数器(用于告警)
|
|
@@ -102,7 +95,7 @@ class RabbitMQClient:
|
|
|
102
95
|
if self._closed:
|
|
103
96
|
return False
|
|
104
97
|
try:
|
|
105
|
-
#
|
|
98
|
+
# 单通道场景:校验通道+连接+核心资源都有效
|
|
106
99
|
return (
|
|
107
100
|
self._channel and not self._channel.is_closed
|
|
108
101
|
and self._channel_conn and not self._channel_conn.is_closed
|
|
@@ -110,23 +103,57 @@ class RabbitMQClient:
|
|
|
110
103
|
and (not self.queue_name or self._queue is not None)
|
|
111
104
|
)
|
|
112
105
|
except Exception as e:
|
|
113
|
-
|
|
106
|
+
logger.warning(f"检查连接状态失败: {str(e)}")
|
|
114
107
|
return False
|
|
115
108
|
|
|
109
|
+
async def _rebuild_resources(self) -> None:
|
|
110
|
+
"""重建交换机/队列等资源(依赖已有的通道)"""
|
|
111
|
+
if not self._channel or self._channel.is_closed:
|
|
112
|
+
raise RuntimeError("无有效通道,无法重建资源")
|
|
113
|
+
|
|
114
|
+
# 1. 声明交换机
|
|
115
|
+
self._exchange = await self._channel.declare_exchange(
|
|
116
|
+
name=self.exchange_name,
|
|
117
|
+
type=self.exchange_type,
|
|
118
|
+
durable=self.durable,
|
|
119
|
+
auto_delete=self.auto_delete,
|
|
120
|
+
passive=not self.create_if_not_exists,
|
|
121
|
+
)
|
|
122
|
+
logger.info(
|
|
123
|
+
f"交换机重建成功: {self.exchange_name}(类型: {self.exchange_type.value})")
|
|
124
|
+
|
|
125
|
+
# 2. 声明队列(如果配置了队列名)
|
|
126
|
+
if self.queue_name:
|
|
127
|
+
self._queue = await self._channel.declare_queue(
|
|
128
|
+
name=self.queue_name,
|
|
129
|
+
durable=self.durable,
|
|
130
|
+
auto_delete=self.auto_delete,
|
|
131
|
+
passive=not self.create_if_not_exists,
|
|
132
|
+
)
|
|
133
|
+
# 绑定队列到交换机
|
|
134
|
+
await self._queue.bind(
|
|
135
|
+
exchange=self._exchange,
|
|
136
|
+
routing_key=self.routing_key,
|
|
137
|
+
)
|
|
138
|
+
logger.info(
|
|
139
|
+
f"队列重建成功: {self.queue_name} "
|
|
140
|
+
f"(绑定交换机: {self.exchange_name}, routing_key: {self.routing_key})"
|
|
141
|
+
)
|
|
142
|
+
|
|
116
143
|
async def connect(self) -> None:
|
|
117
144
|
if self._closed:
|
|
118
145
|
raise RuntimeError("客户端已关闭,无法重新连接")
|
|
119
146
|
|
|
120
147
|
async with self._connect_lock:
|
|
121
|
-
#
|
|
122
|
-
if self.
|
|
148
|
+
# 1. 清理旧连接回调(防止内存泄漏)
|
|
149
|
+
if self._channel_conn and self._conn_close_callback:
|
|
123
150
|
try:
|
|
124
|
-
|
|
125
|
-
self.
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
151
|
+
self._channel_conn.close_callbacks.discard(
|
|
152
|
+
self._conn_close_callback)
|
|
153
|
+
except Exception:
|
|
154
|
+
pass
|
|
155
|
+
|
|
156
|
+
# 2. 清理状态
|
|
130
157
|
self._channel = None
|
|
131
158
|
self._channel_conn = None
|
|
132
159
|
self._exchange = None
|
|
@@ -134,18 +161,14 @@ class RabbitMQClient:
|
|
|
134
161
|
self._conn_close_callback = None
|
|
135
162
|
|
|
136
163
|
try:
|
|
137
|
-
#
|
|
164
|
+
# 3. 获取新通道
|
|
138
165
|
self._channel, self._channel_conn = await self.connection_pool.acquire_channel()
|
|
139
166
|
|
|
167
|
+
# 4. 设置新连接回调(使用 weakref)
|
|
140
168
|
def on_conn_closed(conn: AbstractRobustConnection, exc: Optional[BaseException]):
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
self._reconnect_fail_count += 1
|
|
145
|
-
# 超过阈值告警
|
|
146
|
-
if self._reconnect_fail_count >= self._reconnect_alert_threshold:
|
|
147
|
-
SYLogger.error(
|
|
148
|
-
f"连接失败次数已达阈值({self._reconnect_alert_threshold}),请检查MQ服务状态")
|
|
169
|
+
# 注意:这里需要访问外部的 self,使用闭包或 weakref
|
|
170
|
+
# 简单起见,这里用闭包,但务必在 self.close 或 self.connect 时清理回调
|
|
171
|
+
logger.warning(f"检测到连接关闭: {exc}")
|
|
149
172
|
if not self._closed:
|
|
150
173
|
asyncio.create_task(self._safe_reconnect())
|
|
151
174
|
|
|
@@ -154,97 +177,60 @@ class RabbitMQClient:
|
|
|
154
177
|
self._channel_conn.close_callbacks.add(
|
|
155
178
|
self._conn_close_callback)
|
|
156
179
|
|
|
157
|
-
#
|
|
158
|
-
await self.
|
|
159
|
-
SYLogger.debug(f"设置预取计数: {self.prefetch_count}")
|
|
160
|
-
|
|
161
|
-
# 3. 低版本 RobustChannel 说明:默认启用异步发布确认,无显式确认方法
|
|
162
|
-
SYLogger.debug(
|
|
163
|
-
"基于 RobustChannel 异步发布确认(低版本 aio-pika 不支持显式确认方法)")
|
|
164
|
-
|
|
165
|
-
# 4. 声明交换机
|
|
166
|
-
self._exchange = await self._channel.declare_exchange(
|
|
167
|
-
name=self.exchange_name,
|
|
168
|
-
type=self.exchange_type,
|
|
169
|
-
durable=self.durable,
|
|
170
|
-
auto_delete=self.auto_delete,
|
|
171
|
-
passive=not self.create_if_not_exists, # passive=True时,不存在则报错
|
|
172
|
-
)
|
|
173
|
-
SYLogger.info(
|
|
174
|
-
f"交换机初始化成功: {self.exchange_name}(类型: {self.exchange_type.value})")
|
|
175
|
-
|
|
176
|
-
# 5. 声明队列(如果配置了队列名)
|
|
177
|
-
if self.queue_name:
|
|
178
|
-
self._queue = await self._channel.declare_queue(
|
|
179
|
-
name=self.queue_name,
|
|
180
|
-
durable=self.durable,
|
|
181
|
-
auto_delete=self.auto_delete,
|
|
182
|
-
passive=not self.create_if_not_exists,
|
|
183
|
-
)
|
|
184
|
-
# 绑定队列到交换机
|
|
185
|
-
await self._queue.bind(
|
|
186
|
-
exchange=self._exchange,
|
|
187
|
-
routing_key=self.routing_key,
|
|
188
|
-
)
|
|
189
|
-
SYLogger.info(
|
|
190
|
-
f"队列初始化成功: {self.queue_name} "
|
|
191
|
-
f"(绑定交换机: {self.exchange_name}, routing_key: {self.routing_key})"
|
|
192
|
-
)
|
|
180
|
+
# 5. 重建资源
|
|
181
|
+
await self._rebuild_resources()
|
|
193
182
|
|
|
194
|
-
#
|
|
183
|
+
# 重置计数
|
|
195
184
|
self._reconnect_fail_count = 0
|
|
196
|
-
|
|
185
|
+
logger.info("客户端连接初始化完成")
|
|
197
186
|
except Exception as e:
|
|
198
|
-
|
|
199
|
-
#
|
|
200
|
-
if self.
|
|
201
|
-
self._channel_conn.close_callbacks.discard(
|
|
202
|
-
self._conn_close_callback)
|
|
203
|
-
if self._channel and self._channel_conn:
|
|
187
|
+
logger.error(f"客户端连接失败: {str(e)}", exc_info=True)
|
|
188
|
+
# 失败时也要清理可能产生的残留引用
|
|
189
|
+
if self._channel_conn and self._conn_close_callback:
|
|
204
190
|
try:
|
|
205
|
-
|
|
206
|
-
|
|
191
|
+
self._channel_conn.close_callbacks.discard(
|
|
192
|
+
self._conn_close_callback)
|
|
193
|
+
except Exception:
|
|
207
194
|
pass
|
|
195
|
+
# 清空状态
|
|
208
196
|
self._channel = None
|
|
209
197
|
self._channel_conn = None
|
|
210
|
-
|
|
198
|
+
self._conn_close_callback = None
|
|
199
|
+
|
|
200
|
+
# 触发重连
|
|
211
201
|
if not self._closed:
|
|
212
202
|
asyncio.create_task(self._safe_reconnect())
|
|
213
203
|
raise
|
|
214
204
|
|
|
215
205
|
async def _safe_reconnect(self):
|
|
216
|
-
"""安全重连:信号量控制并发+固定15
|
|
217
|
-
# 1. 信号量控制:限制同时进行的重连任务数(默认1个)
|
|
206
|
+
"""安全重连:信号量控制并发+固定15秒间隔"""
|
|
218
207
|
async with self._reconnect_semaphore:
|
|
219
|
-
#
|
|
208
|
+
# 检查是否已有重连任务在运行
|
|
220
209
|
if self._current_reconnect_task and not self._current_reconnect_task.done():
|
|
221
|
-
|
|
210
|
+
logger.debug("已有重连任务在运行,跳过重复触发")
|
|
222
211
|
return
|
|
223
212
|
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
return
|
|
213
|
+
if self._closed or await self.is_connected:
|
|
214
|
+
logger.debug("客户端已关闭或已连接,取消重连")
|
|
215
|
+
return
|
|
228
216
|
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
217
|
+
# 固定15秒重连间隔
|
|
218
|
+
logger.info(f"将在{self._RECONNECT_INTERVAL}秒后尝试重连...")
|
|
219
|
+
await asyncio.sleep(self._RECONNECT_INTERVAL)
|
|
232
220
|
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
221
|
+
if self._closed or await self.is_connected:
|
|
222
|
+
logger.debug("重连等待期间客户端状态变化,取消重连")
|
|
223
|
+
return
|
|
236
224
|
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
self.
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
finally:
|
|
247
|
-
self._current_reconnect_task = None
|
|
225
|
+
try:
|
|
226
|
+
logger.info("开始重连RabbitMQ客户端...")
|
|
227
|
+
self._current_reconnect_task = asyncio.create_task(
|
|
228
|
+
self.connect())
|
|
229
|
+
await self._current_reconnect_task
|
|
230
|
+
except Exception as e:
|
|
231
|
+
logger.warning(f"重连失败: {str(e)}")
|
|
232
|
+
finally:
|
|
233
|
+
self._current_reconnect_task = None
|
|
248
234
|
|
|
249
235
|
async def set_message_handler(
|
|
250
236
|
self,
|
|
@@ -256,7 +242,7 @@ class RabbitMQClient:
|
|
|
256
242
|
|
|
257
243
|
async with self._consume_lock:
|
|
258
244
|
self._message_handler = handler
|
|
259
|
-
|
|
245
|
+
logger.info("消息处理器设置成功")
|
|
260
246
|
|
|
261
247
|
async def start_consuming(self) -> Optional[ConsumerTag]:
|
|
262
248
|
"""启动消息消费(支持自动重连)"""
|
|
@@ -270,7 +256,7 @@ class RabbitMQClient:
|
|
|
270
256
|
if not await self.is_connected:
|
|
271
257
|
await self.connect()
|
|
272
258
|
if not self._queue:
|
|
273
|
-
raise RuntimeError("
|
|
259
|
+
raise RuntimeError("未配置队列名或队列未创建,无法启动消费")
|
|
274
260
|
|
|
275
261
|
# 2. 定义消费回调(包含异常处理和重连逻辑)
|
|
276
262
|
async def consume_callback(message: AbstractIncomingMessage):
|
|
@@ -282,7 +268,7 @@ class RabbitMQClient:
|
|
|
282
268
|
message.body.decode("utf-8"))
|
|
283
269
|
msg_obj = MQMsgModel(**body_dict)
|
|
284
270
|
except json.JSONDecodeError as e:
|
|
285
|
-
|
|
271
|
+
logger.error(
|
|
286
272
|
f"JSON消息解析失败: {str(e)},消息体: {message.body[:100]}...")
|
|
287
273
|
await message.nack(requeue=False) # 解析失败,不重入队
|
|
288
274
|
return
|
|
@@ -293,51 +279,66 @@ class RabbitMQClient:
|
|
|
293
279
|
delivery_tag=message.delivery_tag,
|
|
294
280
|
)
|
|
295
281
|
|
|
296
|
-
#
|
|
282
|
+
# 调用消息处理器
|
|
297
283
|
await self._message_handler(msg_obj, message)
|
|
298
284
|
|
|
299
|
-
# 手动ACK
|
|
285
|
+
# 手动ACK
|
|
300
286
|
await message.ack()
|
|
301
|
-
|
|
287
|
+
logger.debug(
|
|
302
288
|
f"消息处理成功,delivery_tag: {message.delivery_tag}")
|
|
303
289
|
|
|
304
290
|
except Exception as e:
|
|
305
|
-
|
|
291
|
+
logger.error(
|
|
306
292
|
f"消息处理失败,delivery_tag: {message.delivery_tag}",
|
|
307
293
|
exc_info=True
|
|
308
294
|
)
|
|
309
295
|
# 处理失败逻辑:首次失败重入队,再次失败丢弃
|
|
310
296
|
if message.redelivered:
|
|
311
|
-
|
|
297
|
+
logger.warning(
|
|
312
298
|
f"消息已重入队过,本次拒绝入队: {message.delivery_tag}")
|
|
313
299
|
await message.reject(requeue=False)
|
|
314
300
|
else:
|
|
315
|
-
|
|
301
|
+
logger.warning(f"消息重入队: {message.delivery_tag}")
|
|
316
302
|
await message.nack(requeue=True)
|
|
317
303
|
|
|
318
|
-
#
|
|
304
|
+
# 连接失效则触发重连
|
|
319
305
|
if not await self.is_connected:
|
|
320
|
-
|
|
306
|
+
logger.warning("连接已失效,触发客户端重连")
|
|
321
307
|
asyncio.create_task(self._safe_reconnect())
|
|
322
308
|
|
|
323
|
-
# 3.
|
|
309
|
+
# 3. 启动消费(单通道消费,避免阻塞发布需确保业务回调非阻塞)
|
|
324
310
|
self._consumer_tag = await self._queue.consume(consume_callback)
|
|
325
|
-
|
|
311
|
+
logger.info(
|
|
326
312
|
f"开始消费队列: {self._queue.name},consumer_tag: {self._consumer_tag}"
|
|
327
313
|
)
|
|
328
314
|
return self._consumer_tag
|
|
329
315
|
|
|
330
316
|
async def stop_consuming(self) -> None:
|
|
331
|
-
"""
|
|
317
|
+
"""停止消息消费(适配 RobustChannel)"""
|
|
332
318
|
async with self._consume_lock:
|
|
333
|
-
|
|
334
|
-
|
|
319
|
+
try:
|
|
320
|
+
# 校验核心条件:消费标签、队列、通道均有效
|
|
321
|
+
if self._consumer_tag and self._queue and self._channel and not self._channel.is_closed:
|
|
322
|
+
# 使用队列的 cancel 方法(适配 RobustChannel)
|
|
335
323
|
await self._queue.cancel(self._consumer_tag)
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
324
|
+
logger.info(
|
|
325
|
+
f"停止消费成功,consumer_tag: {self._consumer_tag},队列: {self._queue.name}"
|
|
326
|
+
)
|
|
327
|
+
elif self._consumer_tag:
|
|
328
|
+
# 部分资源无效时的日志提示
|
|
329
|
+
if not self._queue:
|
|
330
|
+
logger.warning(
|
|
331
|
+
f"消费标签存在但队列为空,无法取消消费(consumer_tag: {self._consumer_tag})")
|
|
332
|
+
elif not self._channel or self._channel.is_closed:
|
|
333
|
+
logger.warning(
|
|
334
|
+
f"通道已关闭,消费已自动停止(consumer_tag: {self._consumer_tag},队列: {self._queue.name if self._queue else '未知'})"
|
|
335
|
+
)
|
|
336
|
+
except Exception as e:
|
|
337
|
+
logger.error(
|
|
338
|
+
f"停止消费者 '{self._queue.name if self._queue else '未知队列'}' 时出错: {str(e)}", exc_info=True
|
|
339
|
+
)
|
|
340
|
+
finally:
|
|
341
|
+
self._consumer_tag = None # 无论成败,清理消费标签
|
|
341
342
|
|
|
342
343
|
async def publish(
|
|
343
344
|
self,
|
|
@@ -371,7 +372,7 @@ class RabbitMQClient:
|
|
|
371
372
|
else:
|
|
372
373
|
raise TypeError(f"不支持的消息体类型: {type(message_body)}")
|
|
373
374
|
except Exception as e:
|
|
374
|
-
|
|
375
|
+
logger.error(f"消息体序列化失败: {str(e)}", exc_info=True)
|
|
375
376
|
raise
|
|
376
377
|
|
|
377
378
|
# 构建消息对象
|
|
@@ -387,49 +388,47 @@ class RabbitMQClient:
|
|
|
387
388
|
try:
|
|
388
389
|
# 确保连接有效
|
|
389
390
|
if not await self.is_connected:
|
|
390
|
-
|
|
391
|
+
logger.warning(f"发布消息前连接失效,触发重连(retry: {retry})")
|
|
391
392
|
await self.connect()
|
|
392
393
|
|
|
393
|
-
#
|
|
394
|
+
# 核心:发布消息(mandatory=True 确保路由有效,timeout=5s 避免阻塞)
|
|
394
395
|
publish_result = await self._exchange.publish(
|
|
395
396
|
message=message,
|
|
396
397
|
routing_key=self.routing_key or self.queue_name or "#",
|
|
397
|
-
mandatory=True,
|
|
398
|
-
timeout=5.0
|
|
398
|
+
mandatory=True,
|
|
399
|
+
timeout=5.0
|
|
399
400
|
)
|
|
400
401
|
|
|
401
|
-
# 处理 mandatory
|
|
402
|
+
# 处理 mandatory 未路由场景
|
|
402
403
|
if publish_result is None:
|
|
403
404
|
raise RuntimeError(
|
|
404
405
|
f"消息未找到匹配的队列(routing_key: {self.routing_key}),mandatory=True 触发失败"
|
|
405
406
|
)
|
|
406
407
|
|
|
407
|
-
|
|
408
|
-
SYLogger.info(
|
|
408
|
+
logger.info(
|
|
409
409
|
f"消息发布成功(retry: {retry}),routing_key: {self.routing_key},"
|
|
410
410
|
f"delivery_mode: {delivery_mode.value},mandatory: True,timeout: 5.0s"
|
|
411
411
|
)
|
|
412
412
|
return
|
|
413
413
|
except asyncio.TimeoutError:
|
|
414
|
-
|
|
414
|
+
logger.error(
|
|
415
415
|
f"消息发布超时(retry: {retry}/{retry_count-1}),超时时间: 5.0s"
|
|
416
416
|
)
|
|
417
417
|
except RuntimeError as e:
|
|
418
|
-
|
|
419
|
-
SYLogger.error(
|
|
418
|
+
logger.error(
|
|
420
419
|
f"消息发布业务失败(retry: {retry}/{retry_count-1}): {str(e)}"
|
|
421
420
|
)
|
|
422
421
|
except Exception as e:
|
|
423
|
-
|
|
422
|
+
logger.error(
|
|
424
423
|
f"消息发布失败(retry: {retry}/{retry_count-1}): {str(e)}",
|
|
425
424
|
exc_info=True
|
|
426
425
|
)
|
|
427
426
|
# 清理失效状态,下次重试重连
|
|
428
427
|
self._exchange = None
|
|
429
|
-
#
|
|
428
|
+
# 指数退避重试间隔
|
|
430
429
|
await asyncio.sleep(0.5 * (2 ** retry))
|
|
431
430
|
|
|
432
|
-
#
|
|
431
|
+
# 所有重试失败
|
|
433
432
|
raise RuntimeError(
|
|
434
433
|
f"消息发布失败(已重试{retry_count}次),routing_key: {self.routing_key},"
|
|
435
434
|
f"mandatory: True,timeout: 5.0s"
|
|
@@ -438,7 +437,7 @@ class RabbitMQClient:
|
|
|
438
437
|
async def close(self) -> None:
|
|
439
438
|
"""关闭客户端(移除回调+释放资源)"""
|
|
440
439
|
self._closed = True
|
|
441
|
-
|
|
440
|
+
logger.info("开始关闭RabbitMQ客户端...")
|
|
442
441
|
|
|
443
442
|
# 停止重连任务
|
|
444
443
|
if self._current_reconnect_task and not self._current_reconnect_task.done():
|
|
@@ -446,27 +445,20 @@ class RabbitMQClient:
|
|
|
446
445
|
try:
|
|
447
446
|
await self._current_reconnect_task
|
|
448
447
|
except asyncio.CancelledError:
|
|
449
|
-
|
|
448
|
+
logger.debug("重连任务已取消")
|
|
450
449
|
|
|
451
450
|
# 1. 停止消费
|
|
452
451
|
await self.stop_consuming()
|
|
453
452
|
|
|
454
|
-
# 2.
|
|
453
|
+
# 2. 清理回调+状态(单通道无需归还,连接池统一管理)
|
|
455
454
|
async with self._connect_lock:
|
|
456
|
-
if self.
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
if self._conn_close_callback:
|
|
460
|
-
self._channel_conn.close_callbacks.discard(
|
|
461
|
-
self._conn_close_callback)
|
|
462
|
-
await self.connection_pool.release_channel(self._channel, self._channel_conn)
|
|
463
|
-
SYLogger.info("通道释放成功")
|
|
464
|
-
except Exception as e:
|
|
465
|
-
SYLogger.error(f"通道释放失败: {str(e)}", exc_info=True)
|
|
455
|
+
if self._conn_close_callback and self._channel_conn:
|
|
456
|
+
self._channel_conn.close_callbacks.discard(
|
|
457
|
+
self._conn_close_callback)
|
|
466
458
|
self._channel = None
|
|
467
459
|
self._channel_conn = None
|
|
468
460
|
self._exchange = None
|
|
469
461
|
self._queue = None
|
|
470
462
|
self._message_handler = None
|
|
471
463
|
|
|
472
|
-
|
|
464
|
+
logger.info("RabbitMQ客户端已完全关闭")
|