sycommon-python-lib 0.1.55b0__py3-none-any.whl → 0.1.56__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 +29 -4
- sycommon/config/LangfuseConfig.py +15 -0
- sycommon/config/RerankerConfig.py +1 -0
- sycommon/config/SentryConfig.py +13 -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 +204 -0
- sycommon/llm/get_llm.py +37 -0
- sycommon/llm/llm_logger.py +126 -0
- sycommon/llm/llm_tokens.py +119 -0
- sycommon/llm/struct_token.py +192 -0
- sycommon/llm/sy_langfuse.py +103 -0
- sycommon/llm/usage_token.py +117 -0
- sycommon/logging/async_sql_logger.py +65 -0
- sycommon/logging/kafka_log.py +200 -434
- sycommon/logging/logger_levels.py +23 -0
- sycommon/middleware/context.py +2 -0
- sycommon/middleware/exception.py +10 -16
- sycommon/middleware/timeout.py +2 -1
- sycommon/middleware/traceid.py +174 -48
- sycommon/notice/__init__.py +0 -0
- sycommon/notice/uvicorn_monitor.py +200 -0
- sycommon/rabbitmq/rabbitmq_client.py +232 -242
- sycommon/rabbitmq/rabbitmq_pool.py +278 -218
- sycommon/rabbitmq/rabbitmq_service.py +25 -843
- sycommon/rabbitmq/rabbitmq_service_client_manager.py +206 -0
- sycommon/rabbitmq/rabbitmq_service_connection_monitor.py +73 -0
- sycommon/rabbitmq/rabbitmq_service_consumer_manager.py +285 -0
- sycommon/rabbitmq/rabbitmq_service_core.py +117 -0
- sycommon/rabbitmq/rabbitmq_service_producer_manager.py +238 -0
- sycommon/sentry/__init__.py +0 -0
- sycommon/sentry/sy_sentry.py +35 -0
- sycommon/services.py +132 -103
- sycommon/synacos/feign.py +8 -3
- sycommon/synacos/feign_client.py +22 -8
- sycommon/synacos/nacos_client_base.py +119 -0
- sycommon/synacos/nacos_config_manager.py +107 -0
- sycommon/synacos/nacos_heartbeat_manager.py +144 -0
- sycommon/synacos/nacos_service.py +64 -771
- sycommon/synacos/nacos_service_discovery.py +157 -0
- sycommon/synacos/nacos_service_registration.py +270 -0
- sycommon/tools/env.py +62 -0
- sycommon/tools/merge_headers.py +117 -0
- sycommon/tools/snowflake.py +133 -120
- {sycommon_python_lib-0.1.55b0.dist-info → sycommon_python_lib-0.1.56.dist-info}/METADATA +13 -6
- sycommon_python_lib-0.1.56.dist-info/RECORD +89 -0
- sycommon_python_lib-0.1.55b0.dist-info/RECORD +0 -59
- {sycommon_python_lib-0.1.55b0.dist-info → sycommon_python_lib-0.1.56.dist-info}/WHEEL +0 -0
- {sycommon_python_lib-0.1.55b0.dist-info → sycommon_python_lib-0.1.56.dist-info}/entry_points.txt +0 -0
- {sycommon_python_lib-0.1.55b0.dist-info → sycommon_python_lib-0.1.56.dist-info}/top_level.txt +0 -0
|
@@ -1,9 +1,7 @@
|
|
|
1
|
-
from aio_pika import Channel
|
|
2
|
-
from typing import Optional
|
|
3
1
|
import asyncio
|
|
4
2
|
import json
|
|
5
|
-
from typing import Callable, Coroutine, Dict, Any, Union
|
|
6
|
-
from aio_pika import Message, DeliveryMode, ExchangeType
|
|
3
|
+
from typing import Optional, Callable, Coroutine, Dict, Any, Union
|
|
4
|
+
from aio_pika import Channel, Message, DeliveryMode, ExchangeType
|
|
7
5
|
from aio_pika.abc import (
|
|
8
6
|
AbstractExchange,
|
|
9
7
|
AbstractQueue,
|
|
@@ -20,13 +18,7 @@ logger = SYLogger
|
|
|
20
18
|
|
|
21
19
|
class RabbitMQClient:
|
|
22
20
|
"""
|
|
23
|
-
RabbitMQ
|
|
24
|
-
核心特性:
|
|
25
|
-
1. 基于单通道连接池复用资源,性能优化
|
|
26
|
-
2. 依赖连接池原生自动重连,客户端仅重建自身资源
|
|
27
|
-
3. 消息发布支持重试+mandatory机制+超时控制,确保路由有效
|
|
28
|
-
4. 消费支持手动ACK/NACK
|
|
29
|
-
5. 兼容JSON/字符串/字典消息格式
|
|
21
|
+
RabbitMQ 客户端
|
|
30
22
|
"""
|
|
31
23
|
|
|
32
24
|
def __init__(
|
|
@@ -42,12 +34,10 @@ class RabbitMQClient:
|
|
|
42
34
|
create_if_not_exists: bool = True,
|
|
43
35
|
**kwargs,
|
|
44
36
|
):
|
|
45
|
-
# 依赖注入:连接池(必须已初始化)
|
|
46
37
|
self.connection_pool = connection_pool
|
|
47
38
|
if not self.connection_pool._initialized:
|
|
48
39
|
raise RuntimeError("连接池未初始化,请先调用 connection_pool.init_pools()")
|
|
49
40
|
|
|
50
|
-
# 交换机配置
|
|
51
41
|
self.exchange_name = exchange_name.strip()
|
|
52
42
|
try:
|
|
53
43
|
self.exchange_type = ExchangeType(exchange_type.lower())
|
|
@@ -55,17 +45,16 @@ class RabbitMQClient:
|
|
|
55
45
|
logger.warning(f"无效的exchange_type: {exchange_type},默认使用'topic'")
|
|
56
46
|
self.exchange_type = ExchangeType.TOPIC
|
|
57
47
|
|
|
58
|
-
# 队列配置
|
|
59
48
|
self.queue_name = queue_name.strip() if queue_name else None
|
|
60
49
|
self.routing_key = routing_key.strip() if routing_key else "#"
|
|
61
|
-
self.durable = durable
|
|
62
|
-
self.auto_delete = auto_delete
|
|
63
|
-
self.auto_parse_json = auto_parse_json
|
|
64
|
-
self.create_if_not_exists = create_if_not_exists
|
|
50
|
+
self.durable = durable
|
|
51
|
+
self.auto_delete = auto_delete
|
|
52
|
+
self.auto_parse_json = auto_parse_json
|
|
53
|
+
self.create_if_not_exists = create_if_not_exists
|
|
65
54
|
|
|
66
|
-
#
|
|
55
|
+
# 资源状态
|
|
67
56
|
self._channel: Optional[Channel] = None
|
|
68
|
-
self._channel_conn: Optional[AbstractRobustConnection] = None
|
|
57
|
+
self._channel_conn: Optional[AbstractRobustConnection] = None
|
|
69
58
|
self._exchange: Optional[AbstractExchange] = None
|
|
70
59
|
self._queue: Optional[AbstractQueue] = None
|
|
71
60
|
self._consumer_tag: Optional[ConsumerTag] = None
|
|
@@ -73,45 +62,38 @@ class RabbitMQClient:
|
|
|
73
62
|
MQMsgModel, AbstractIncomingMessage], Coroutine[Any, Any, None]]] = None
|
|
74
63
|
self._closed = False
|
|
75
64
|
|
|
76
|
-
#
|
|
65
|
+
# 并发控制
|
|
77
66
|
self._consume_lock = asyncio.Lock()
|
|
78
67
|
self._connect_lock = asyncio.Lock()
|
|
79
|
-
|
|
68
|
+
|
|
69
|
+
# 防止并发重连覆盖
|
|
70
|
+
self._connecting = False
|
|
71
|
+
self._connect_condition = asyncio.Condition()
|
|
72
|
+
|
|
80
73
|
self._conn_close_callback: Optional[Callable] = None
|
|
81
|
-
# 控制重连频率的信号量(限制并发重连数)
|
|
82
74
|
self._reconnect_semaphore = asyncio.Semaphore(1)
|
|
83
|
-
# 固定重连间隔15秒(全局统一)
|
|
84
|
-
self._RECONNECT_INTERVAL = 15
|
|
85
|
-
# 跟踪当前重连任务(避免重复创建)
|
|
86
75
|
self._current_reconnect_task: Optional[asyncio.Task] = None
|
|
87
|
-
|
|
88
|
-
self._reconnect_fail_count = 0
|
|
89
|
-
# 连接失败告警阈值
|
|
90
|
-
self._reconnect_alert_threshold = 5
|
|
76
|
+
self._RECONNECT_INTERVAL = 15
|
|
91
77
|
|
|
92
78
|
@property
|
|
93
79
|
async def is_connected(self) -> bool:
|
|
94
|
-
"""异步检查客户端连接状态(属性,不可调用)"""
|
|
95
80
|
if self._closed:
|
|
96
81
|
return False
|
|
97
82
|
try:
|
|
98
|
-
# 单通道场景:校验通道+连接+核心资源都有效
|
|
99
83
|
return (
|
|
100
84
|
self._channel and not self._channel.is_closed
|
|
101
85
|
and self._channel_conn and not self._channel_conn.is_closed
|
|
102
86
|
and self._exchange is not None
|
|
103
87
|
and (not self.queue_name or self._queue is not None)
|
|
104
88
|
)
|
|
105
|
-
except Exception
|
|
106
|
-
logger.warning(f"检查连接状态失败: {str(e)}")
|
|
89
|
+
except Exception:
|
|
107
90
|
return False
|
|
108
91
|
|
|
109
92
|
async def _rebuild_resources(self) -> None:
|
|
110
|
-
"""重建交换机/队列等资源(依赖已有的通道)"""
|
|
111
93
|
if not self._channel or self._channel.is_closed:
|
|
112
94
|
raise RuntimeError("无有效通道,无法重建资源")
|
|
113
95
|
|
|
114
|
-
#
|
|
96
|
+
# 声明交换机
|
|
115
97
|
self._exchange = await self._channel.declare_exchange(
|
|
116
98
|
name=self.exchange_name,
|
|
117
99
|
type=self.exchange_type,
|
|
@@ -119,10 +101,9 @@ class RabbitMQClient:
|
|
|
119
101
|
auto_delete=self.auto_delete,
|
|
120
102
|
passive=not self.create_if_not_exists,
|
|
121
103
|
)
|
|
122
|
-
logger.info(
|
|
123
|
-
f"交换机重建成功: {self.exchange_name}(类型: {self.exchange_type.value})")
|
|
104
|
+
logger.info(f"交换机重建成功: {self.exchange_name}")
|
|
124
105
|
|
|
125
|
-
#
|
|
106
|
+
# 声明队列
|
|
126
107
|
if self.queue_name:
|
|
127
108
|
self._queue = await self._channel.declare_queue(
|
|
128
109
|
name=self.queue_name,
|
|
@@ -130,93 +111,134 @@ class RabbitMQClient:
|
|
|
130
111
|
auto_delete=self.auto_delete,
|
|
131
112
|
passive=not self.create_if_not_exists,
|
|
132
113
|
)
|
|
133
|
-
|
|
134
|
-
|
|
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
|
-
)
|
|
114
|
+
await self._queue.bind(exchange=self._exchange, routing_key=self.routing_key)
|
|
115
|
+
logger.info(f"队列重建成功: {self.queue_name}")
|
|
142
116
|
|
|
143
117
|
async def connect(self) -> None:
|
|
144
118
|
if self._closed:
|
|
145
119
|
raise RuntimeError("客户端已关闭,无法重新连接")
|
|
146
120
|
|
|
121
|
+
# 1. 并发控制:使用 _connect_lock 保证只有一个协程在执行连接流程
|
|
147
122
|
async with self._connect_lock:
|
|
148
|
-
#
|
|
149
|
-
if self.
|
|
150
|
-
|
|
123
|
+
# 如果已经在连了,等待其完成
|
|
124
|
+
if self._connecting:
|
|
125
|
+
logger.debug("连接正在进行中,等待现有连接完成...")
|
|
126
|
+
try:
|
|
127
|
+
# 等待条件变量,超时设为 60 秒防止死等
|
|
128
|
+
await asyncio.wait_for(
|
|
129
|
+
self._connect_condition.wait_for(
|
|
130
|
+
lambda: not self._connecting),
|
|
131
|
+
timeout=60.0
|
|
132
|
+
)
|
|
133
|
+
except asyncio.TimeoutError:
|
|
134
|
+
raise RuntimeError("等待连接超时")
|
|
135
|
+
|
|
136
|
+
# 等待结束后,再次检查状态
|
|
137
|
+
if not await self.is_connected:
|
|
138
|
+
raise RuntimeError("等待重连后,连接状态依然无效")
|
|
139
|
+
return
|
|
140
|
+
|
|
141
|
+
# 标记开始连接
|
|
142
|
+
self._connecting = True
|
|
143
|
+
|
|
144
|
+
# 释放 _connect_lock,允许其他协程读取状态,但在连接完成前阻止新的连接请求
|
|
145
|
+
# 注意:这里释放了 _connect_lock,但 self._connecting = True 阻止了新的连接流程
|
|
146
|
+
|
|
147
|
+
try:
|
|
148
|
+
# --- 阶段1: 清理旧资源 ---
|
|
149
|
+
# 重新获取锁进行资源清理
|
|
150
|
+
async with self._connect_lock:
|
|
151
|
+
was_consuming = self._consumer_tag is not None
|
|
152
|
+
|
|
153
|
+
if self._channel_conn and self._conn_close_callback:
|
|
154
|
+
try:
|
|
155
|
+
self._channel_conn.close_callbacks.discard(
|
|
156
|
+
self._conn_close_callback)
|
|
157
|
+
except Exception:
|
|
158
|
+
pass
|
|
159
|
+
|
|
160
|
+
self._channel = None
|
|
161
|
+
self._channel_conn = None
|
|
162
|
+
self._exchange = None
|
|
163
|
+
self._queue = None
|
|
164
|
+
self._conn_close_callback = None
|
|
165
|
+
|
|
166
|
+
# --- 阶段2: 获取新连接 (耗时IO) ---
|
|
167
|
+
self._channel, self._channel_conn = await self.connection_pool.acquire_channel()
|
|
168
|
+
|
|
169
|
+
# 设置回调
|
|
170
|
+
def on_conn_closed(conn, exc):
|
|
171
|
+
logger.warning(f"检测到连接关闭: {exc}")
|
|
172
|
+
if not self._closed and not self._connecting:
|
|
173
|
+
asyncio.create_task(self._safe_reconnect())
|
|
174
|
+
|
|
175
|
+
self._conn_close_callback = on_conn_closed
|
|
176
|
+
if self._channel_conn:
|
|
177
|
+
self._channel_conn.close_callbacks.add(
|
|
151
178
|
self._conn_close_callback)
|
|
152
|
-
self._channel = None
|
|
153
|
-
self._channel_conn = None
|
|
154
|
-
self._exchange = None
|
|
155
|
-
self._queue = None
|
|
156
|
-
self._conn_close_callback = None
|
|
157
179
|
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
self.
|
|
177
|
-
|
|
180
|
+
# 重建资源
|
|
181
|
+
await self._rebuild_resources()
|
|
182
|
+
|
|
183
|
+
# --- 阶段3: 恢复消费 ---
|
|
184
|
+
if was_consuming and self._message_handler and self.queue_name:
|
|
185
|
+
logger.info("🔄 检测到重连前处于消费状态,尝试自动恢复...")
|
|
186
|
+
try:
|
|
187
|
+
self._queue = await self._channel.declare_queue(
|
|
188
|
+
name=self.queue_name,
|
|
189
|
+
durable=self.durable,
|
|
190
|
+
auto_delete=self.auto_delete,
|
|
191
|
+
passive=False,
|
|
192
|
+
)
|
|
193
|
+
await self._queue.bind(exchange=self._exchange, routing_key=self.routing_key)
|
|
194
|
+
self._consumer_tag = await self._queue.consume(self._process_message_callback)
|
|
195
|
+
logger.info(f"✅ 消费已自动恢复: {self._consumer_tag}")
|
|
196
|
+
except Exception as e:
|
|
197
|
+
logger.error(f"❌ 自动恢复消费失败: {e}")
|
|
198
|
+
self._consumer_tag = None
|
|
199
|
+
else:
|
|
200
|
+
self._consumer_tag = None
|
|
178
201
|
|
|
179
|
-
|
|
180
|
-
await self._rebuild_resources()
|
|
202
|
+
logger.info("客户端连接初始化完成")
|
|
181
203
|
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
if self._conn_close_callback and self._channel_conn:
|
|
204
|
+
except Exception as e:
|
|
205
|
+
logger.error(f"客户端连接失败: {str(e)}", exc_info=True)
|
|
206
|
+
|
|
207
|
+
# 异常时清理资源
|
|
208
|
+
async with self._connect_lock:
|
|
209
|
+
if self._channel_conn and self._conn_close_callback:
|
|
189
210
|
self._channel_conn.close_callbacks.discard(
|
|
190
211
|
self._conn_close_callback)
|
|
191
212
|
self._channel = None
|
|
192
213
|
self._channel_conn = None
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
214
|
+
self._consumer_tag = None
|
|
215
|
+
|
|
216
|
+
raise
|
|
217
|
+
|
|
218
|
+
finally:
|
|
219
|
+
# 【关键修复】必须在持有 Condition 内部锁的情况下调用 notify_all
|
|
220
|
+
# 这里使用 async with self._connect_condition: 自动完成 acquire() ... notify_all() ... release()
|
|
221
|
+
async with self._connect_condition:
|
|
222
|
+
self._connecting = False
|
|
223
|
+
self._connect_condition.notify_all()
|
|
197
224
|
|
|
198
225
|
async def _safe_reconnect(self):
|
|
199
|
-
"""
|
|
226
|
+
"""安全重连任务(仅用于被动监听连接关闭)"""
|
|
200
227
|
async with self._reconnect_semaphore:
|
|
201
|
-
|
|
202
|
-
if self._current_reconnect_task and not self._current_reconnect_task.done():
|
|
203
|
-
logger.debug("已有重连任务在运行,跳过重复触发")
|
|
228
|
+
if self._closed:
|
|
204
229
|
return
|
|
205
230
|
|
|
206
|
-
|
|
207
|
-
|
|
231
|
+
# 如果已经在重连,直接忽略
|
|
232
|
+
if self._connecting:
|
|
208
233
|
return
|
|
209
234
|
|
|
210
|
-
# 固定15秒重连间隔
|
|
211
235
|
logger.info(f"将在{self._RECONNECT_INTERVAL}秒后尝试重连...")
|
|
212
236
|
await asyncio.sleep(self._RECONNECT_INTERVAL)
|
|
213
237
|
|
|
214
238
|
if self._closed or await self.is_connected:
|
|
215
|
-
logger.debug("重连等待期间客户端状态变化,取消重连")
|
|
216
239
|
return
|
|
217
240
|
|
|
218
241
|
try:
|
|
219
|
-
logger.info("开始重连RabbitMQ客户端...")
|
|
220
242
|
self._current_reconnect_task = asyncio.create_task(
|
|
221
243
|
self.connect())
|
|
222
244
|
await self._current_reconnect_task
|
|
@@ -225,113 +247,111 @@ class RabbitMQClient:
|
|
|
225
247
|
finally:
|
|
226
248
|
self._current_reconnect_task = None
|
|
227
249
|
|
|
228
|
-
async def set_message_handler(
|
|
229
|
-
self,
|
|
230
|
-
handler: Callable[[MQMsgModel, AbstractIncomingMessage], Coroutine[Any, Any, None]],
|
|
231
|
-
) -> None:
|
|
232
|
-
"""设置消息处理器(必须是协程函数)"""
|
|
250
|
+
async def set_message_handler(self, handler: Callable[..., Coroutine]) -> None:
|
|
233
251
|
if not asyncio.iscoroutinefunction(handler):
|
|
234
|
-
raise TypeError("
|
|
235
|
-
|
|
252
|
+
raise TypeError("消息处理器必须是协程函数")
|
|
236
253
|
async with self._consume_lock:
|
|
237
254
|
self._message_handler = handler
|
|
238
|
-
|
|
255
|
+
|
|
256
|
+
async def _process_message_callback(self, message: AbstractIncomingMessage):
|
|
257
|
+
try:
|
|
258
|
+
msg_obj: MQMsgModel
|
|
259
|
+
if self.auto_parse_json:
|
|
260
|
+
try:
|
|
261
|
+
body_dict = json.loads(message.body.decode("utf-8"))
|
|
262
|
+
msg_obj = MQMsgModel(**body_dict)
|
|
263
|
+
except json.JSONDecodeError as e:
|
|
264
|
+
logger.error(f"JSON解析失败: {e}")
|
|
265
|
+
await message.nack(requeue=False)
|
|
266
|
+
return
|
|
267
|
+
else:
|
|
268
|
+
msg_obj = MQMsgModel(
|
|
269
|
+
body=message.body.decode("utf-8"),
|
|
270
|
+
routing_key=message.routing_key,
|
|
271
|
+
delivery_tag=message.delivery_tag,
|
|
272
|
+
traceId=message.headers.get("trace-id"),
|
|
273
|
+
)
|
|
274
|
+
|
|
275
|
+
SYLogger.set_trace_id(msg_obj.traceId)
|
|
276
|
+
|
|
277
|
+
if self._message_handler:
|
|
278
|
+
await self._message_handler(msg_obj, message)
|
|
279
|
+
|
|
280
|
+
await message.ack()
|
|
281
|
+
|
|
282
|
+
except Exception as e:
|
|
283
|
+
logger.error(f"消息处理异常: {e}", exc_info=True)
|
|
284
|
+
headers = dict(message.headers) if message.headers else {}
|
|
285
|
+
current_retry = int(headers.get("x-retry-count", 0))
|
|
286
|
+
|
|
287
|
+
if current_retry >= 3:
|
|
288
|
+
logger.warning(f"重试次数超限,丢弃消息: {message.delivery_tag}")
|
|
289
|
+
await message.reject(requeue=False)
|
|
290
|
+
else:
|
|
291
|
+
headers["x-retry-count"] = current_retry + 1
|
|
292
|
+
try:
|
|
293
|
+
new_msg = Message(
|
|
294
|
+
body=message.body,
|
|
295
|
+
headers=headers,
|
|
296
|
+
content_type=message.content_type,
|
|
297
|
+
delivery_mode=message.delivery_mode
|
|
298
|
+
)
|
|
299
|
+
# 这里的 publish 如果失败,会触发重连机制
|
|
300
|
+
# 但注意,当前是在回调线程中,建议做好异常捕获
|
|
301
|
+
await self._exchange.publish(new_msg, routing_key=message.routing_key)
|
|
302
|
+
await message.ack()
|
|
303
|
+
except Exception as pub_err:
|
|
304
|
+
logger.error(f"重试发布失败: {pub_err}")
|
|
305
|
+
await message.reject(requeue=False)
|
|
239
306
|
|
|
240
307
|
async def start_consuming(self) -> Optional[ConsumerTag]:
|
|
241
|
-
"""启动消息消费(支持自动重连)"""
|
|
242
308
|
if self._closed:
|
|
243
309
|
raise RuntimeError("客户端已关闭,无法启动消费")
|
|
244
310
|
|
|
245
311
|
async with self._consume_lock:
|
|
246
|
-
# 1. 校验前置条件
|
|
247
312
|
if not self._message_handler:
|
|
248
|
-
raise RuntimeError("
|
|
313
|
+
raise RuntimeError("未设置消息处理器")
|
|
314
|
+
|
|
249
315
|
if not await self.is_connected:
|
|
250
316
|
await self.connect()
|
|
251
|
-
if not self._queue:
|
|
252
|
-
raise RuntimeError("未配置队列名或队列未创建,无法启动消费")
|
|
253
|
-
|
|
254
|
-
# 2. 定义消费回调(包含异常处理和重连逻辑)
|
|
255
|
-
async def consume_callback(message: AbstractIncomingMessage):
|
|
256
|
-
try:
|
|
257
|
-
# 解析消息体
|
|
258
|
-
if self.auto_parse_json:
|
|
259
|
-
try:
|
|
260
|
-
body_dict = json.loads(
|
|
261
|
-
message.body.decode("utf-8"))
|
|
262
|
-
msg_obj = MQMsgModel(**body_dict)
|
|
263
|
-
except json.JSONDecodeError as e:
|
|
264
|
-
logger.error(
|
|
265
|
-
f"JSON消息解析失败: {str(e)},消息体: {message.body[:100]}...")
|
|
266
|
-
await message.nack(requeue=False) # 解析失败,不重入队
|
|
267
|
-
return
|
|
268
|
-
else:
|
|
269
|
-
msg_obj = MQMsgModel(
|
|
270
|
-
body=message.body.decode("utf-8"),
|
|
271
|
-
routing_key=message.routing_key,
|
|
272
|
-
delivery_tag=message.delivery_tag,
|
|
273
|
-
)
|
|
274
|
-
|
|
275
|
-
# 调用消息处理器
|
|
276
|
-
await self._message_handler(msg_obj, message)
|
|
277
|
-
|
|
278
|
-
# 手动ACK
|
|
279
|
-
await message.ack()
|
|
280
|
-
logger.debug(
|
|
281
|
-
f"消息处理成功,delivery_tag: {message.delivery_tag}")
|
|
282
317
|
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
318
|
+
if not self._queue:
|
|
319
|
+
if self.queue_name:
|
|
320
|
+
self._queue = await self._channel.declare_queue(
|
|
321
|
+
name=self.queue_name,
|
|
322
|
+
durable=self.durable,
|
|
323
|
+
auto_delete=self.auto_delete,
|
|
324
|
+
passive=not self.create_if_not_exists,
|
|
287
325
|
)
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
else:
|
|
294
|
-
logger.warning(f"消息重入队: {message.delivery_tag}")
|
|
295
|
-
await message.nack(requeue=True)
|
|
296
|
-
|
|
297
|
-
# 连接失效则触发重连
|
|
298
|
-
if not await self.is_connected:
|
|
299
|
-
logger.warning("连接已失效,触发客户端重连")
|
|
300
|
-
asyncio.create_task(self._safe_reconnect())
|
|
301
|
-
|
|
302
|
-
# 3. 启动消费(单通道消费,避免阻塞发布需确保业务回调非阻塞)
|
|
303
|
-
self._consumer_tag = await self._queue.consume(consume_callback)
|
|
326
|
+
await self._queue.bind(exchange=self._exchange, routing_key=self.routing_key)
|
|
327
|
+
else:
|
|
328
|
+
raise RuntimeError("未配置队列名")
|
|
329
|
+
|
|
330
|
+
self._consumer_tag = await self._queue.consume(self._process_message_callback)
|
|
304
331
|
logger.info(
|
|
305
|
-
f"开始消费队列: {self._queue.name},
|
|
306
|
-
)
|
|
332
|
+
f"开始消费队列: {self._queue.name},tag: {self._consumer_tag}")
|
|
307
333
|
return self._consumer_tag
|
|
308
334
|
|
|
309
335
|
async def stop_consuming(self) -> None:
|
|
310
|
-
"""停止消息消费(适配 RobustChannel)"""
|
|
311
336
|
async with self._consume_lock:
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
if self._consumer_tag and self._queue and self._channel and not self._channel.is_closed:
|
|
315
|
-
# 使用队列的 cancel 方法(适配 RobustChannel)
|
|
337
|
+
if self._consumer_tag and self._queue and self._channel:
|
|
338
|
+
try:
|
|
316
339
|
await self._queue.cancel(self._consumer_tag)
|
|
317
|
-
logger.info(
|
|
318
|
-
|
|
319
|
-
)
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
)
|
|
333
|
-
finally:
|
|
334
|
-
self._consumer_tag = None # 无论成败,清理消费标签
|
|
340
|
+
logger.info(f"停止消费成功: {self._consumer_tag}")
|
|
341
|
+
except Exception as e:
|
|
342
|
+
logger.warning(f"停止消费异常: {e}")
|
|
343
|
+
self._consumer_tag = None
|
|
344
|
+
|
|
345
|
+
async def _handle_publish_failure(self):
|
|
346
|
+
try:
|
|
347
|
+
logger.info("检测到发布异常,强制连接池切换节点...")
|
|
348
|
+
await self.connection_pool.force_reconnect()
|
|
349
|
+
# 连接池切换后,必须刷新客户端资源
|
|
350
|
+
await self.connect()
|
|
351
|
+
logger.info("故障转移完成,资源已刷新")
|
|
352
|
+
except Exception as e:
|
|
353
|
+
logger.error(f"故障转移失败: {e}")
|
|
354
|
+
raise
|
|
335
355
|
|
|
336
356
|
async def publish(
|
|
337
357
|
self,
|
|
@@ -341,18 +361,9 @@ class RabbitMQClient:
|
|
|
341
361
|
delivery_mode: DeliveryMode = DeliveryMode.PERSISTENT,
|
|
342
362
|
retry_count: int = 3,
|
|
343
363
|
) -> None:
|
|
344
|
-
"""
|
|
345
|
-
发布消息(支持自动重试、mandatory路由校验、5秒超时控制)
|
|
346
|
-
:param message_body: 消息体(字符串/字典/MQMsgModel)
|
|
347
|
-
:param headers: 消息头(可选)
|
|
348
|
-
:param content_type: 内容类型(默认application/json)
|
|
349
|
-
:param delivery_mode: 投递模式(PERSISTENT=持久化,TRANSIENT=非持久化)
|
|
350
|
-
:param retry_count: 重试次数(默认3次)
|
|
351
|
-
"""
|
|
352
364
|
if self._closed:
|
|
353
365
|
raise RuntimeError("客户端已关闭,无法发布消息")
|
|
354
366
|
|
|
355
|
-
# 处理消息体序列化
|
|
356
367
|
try:
|
|
357
368
|
if isinstance(message_body, MQMsgModel):
|
|
358
369
|
body = json.dumps(message_body.to_dict(),
|
|
@@ -365,93 +376,72 @@ class RabbitMQClient:
|
|
|
365
376
|
else:
|
|
366
377
|
raise TypeError(f"不支持的消息体类型: {type(message_body)}")
|
|
367
378
|
except Exception as e:
|
|
368
|
-
logger.error(f"消息体序列化失败: {
|
|
379
|
+
logger.error(f"消息体序列化失败: {e}")
|
|
369
380
|
raise
|
|
370
381
|
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
headers=headers or {},
|
|
375
|
-
content_type=content_type,
|
|
376
|
-
delivery_mode=delivery_mode,
|
|
377
|
-
)
|
|
382
|
+
message = Message(body=body, headers=headers or {},
|
|
383
|
+
content_type=content_type, delivery_mode=delivery_mode)
|
|
384
|
+
last_exception = None
|
|
378
385
|
|
|
379
|
-
# 发布重试逻辑
|
|
380
386
|
for retry in range(retry_count):
|
|
381
387
|
try:
|
|
382
|
-
# 确保连接有效
|
|
383
388
|
if not await self.is_connected:
|
|
384
|
-
logger.warning(f"发布消息前连接失效,触发重连(retry: {retry})")
|
|
385
389
|
await self.connect()
|
|
386
390
|
|
|
387
|
-
|
|
388
|
-
publish_result = await self._exchange.publish(
|
|
391
|
+
result = await self._exchange.publish(
|
|
389
392
|
message=message,
|
|
390
393
|
routing_key=self.routing_key or self.queue_name or "#",
|
|
391
394
|
mandatory=True,
|
|
392
395
|
timeout=5.0
|
|
393
396
|
)
|
|
394
397
|
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
raise RuntimeError(
|
|
398
|
-
f"消息未找到匹配的队列(routing_key: {self.routing_key}),mandatory=True 触发失败"
|
|
399
|
-
)
|
|
398
|
+
if result is None:
|
|
399
|
+
raise RuntimeError(f"消息未找到匹配的队列: {self.routing_key}")
|
|
400
400
|
|
|
401
|
-
logger.info(
|
|
402
|
-
f"消息发布成功(retry: {retry}),routing_key: {self.routing_key},"
|
|
403
|
-
f"delivery_mode: {delivery_mode.value},mandatory: True,timeout: 5.0s"
|
|
404
|
-
)
|
|
401
|
+
logger.info(f"发布成功: {self.routing_key}")
|
|
405
402
|
return
|
|
406
|
-
|
|
407
|
-
logger.error(
|
|
408
|
-
f"消息发布超时(retry: {retry}/{retry_count-1}),超时时间: 5.0s"
|
|
409
|
-
)
|
|
403
|
+
|
|
410
404
|
except RuntimeError as e:
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
)
|
|
405
|
+
if "未找到匹配的队列" in str(e):
|
|
406
|
+
raise
|
|
407
|
+
last_exception = str(e)
|
|
408
|
+
await self._handle_publish_failure()
|
|
409
|
+
|
|
414
410
|
except Exception as e:
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
)
|
|
419
|
-
# 清理失效状态,下次重试重连
|
|
420
|
-
self._exchange = None
|
|
421
|
-
# 指数退避重试间隔
|
|
422
|
-
await asyncio.sleep(0.5 * (2 ** retry))
|
|
411
|
+
last_exception = str(e)
|
|
412
|
+
logger.error(f"发布异常: {e}")
|
|
413
|
+
await self._handle_publish_failure()
|
|
423
414
|
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
f"mandatory: True,timeout: 5.0s"
|
|
428
|
-
)
|
|
415
|
+
await asyncio.sleep(5)
|
|
416
|
+
|
|
417
|
+
raise RuntimeError(f"消息发布最终失败: {last_exception}")
|
|
429
418
|
|
|
430
419
|
async def close(self) -> None:
|
|
431
|
-
"""关闭客户端(移除回调+释放资源)"""
|
|
432
420
|
self._closed = True
|
|
433
421
|
logger.info("开始关闭RabbitMQ客户端...")
|
|
434
422
|
|
|
435
|
-
# 停止重连任务
|
|
436
423
|
if self._current_reconnect_task and not self._current_reconnect_task.done():
|
|
437
424
|
self._current_reconnect_task.cancel()
|
|
438
425
|
try:
|
|
439
426
|
await self._current_reconnect_task
|
|
440
427
|
except asyncio.CancelledError:
|
|
441
|
-
|
|
428
|
+
pass
|
|
442
429
|
|
|
443
|
-
# 1. 停止消费
|
|
444
430
|
await self.stop_consuming()
|
|
445
431
|
|
|
446
|
-
# 2. 清理回调+状态(单通道无需归还,连接池统一管理)
|
|
447
432
|
async with self._connect_lock:
|
|
448
433
|
if self._conn_close_callback and self._channel_conn:
|
|
449
434
|
self._channel_conn.close_callbacks.discard(
|
|
450
435
|
self._conn_close_callback)
|
|
436
|
+
|
|
451
437
|
self._channel = None
|
|
452
438
|
self._channel_conn = None
|
|
453
439
|
self._exchange = None
|
|
454
440
|
self._queue = None
|
|
455
441
|
self._message_handler = None
|
|
456
442
|
|
|
457
|
-
|
|
443
|
+
# 确保唤醒可能正在等待 connect 的任务
|
|
444
|
+
self._connecting = False
|
|
445
|
+
self._connect_condition.notify_all()
|
|
446
|
+
|
|
447
|
+
logger.info("客户端已关闭")
|