sycommon-python-lib 0.1.56__py3-none-any.whl → 0.1.56b2__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 +3 -24
- sycommon/llm/embedding.py +23 -78
- sycommon/llm/get_llm.py +164 -24
- sycommon/logging/kafka_log.py +433 -187
- sycommon/middleware/exception.py +16 -10
- sycommon/middleware/timeout.py +1 -2
- sycommon/middleware/traceid.py +76 -81
- sycommon/rabbitmq/rabbitmq_client.py +242 -232
- sycommon/rabbitmq/rabbitmq_pool.py +218 -278
- sycommon/rabbitmq/rabbitmq_service.py +843 -25
- sycommon/services.py +96 -122
- sycommon/synacos/nacos_service.py +779 -63
- sycommon/tools/merge_headers.py +0 -20
- sycommon/tools/snowflake.py +153 -101
- {sycommon_python_lib-0.1.56.dist-info → sycommon_python_lib-0.1.56b2.dist-info}/METADATA +8 -10
- {sycommon_python_lib-0.1.56.dist-info → sycommon_python_lib-0.1.56b2.dist-info}/RECORD +19 -40
- sycommon/config/LangfuseConfig.py +0 -15
- sycommon/config/SentryConfig.py +0 -13
- sycommon/llm/llm_tokens.py +0 -119
- sycommon/llm/struct_token.py +0 -192
- sycommon/llm/sy_langfuse.py +0 -103
- sycommon/llm/usage_token.py +0 -117
- sycommon/notice/__init__.py +0 -0
- sycommon/notice/uvicorn_monitor.py +0 -200
- sycommon/rabbitmq/rabbitmq_service_client_manager.py +0 -206
- sycommon/rabbitmq/rabbitmq_service_connection_monitor.py +0 -73
- sycommon/rabbitmq/rabbitmq_service_consumer_manager.py +0 -285
- sycommon/rabbitmq/rabbitmq_service_core.py +0 -117
- sycommon/rabbitmq/rabbitmq_service_producer_manager.py +0 -238
- sycommon/sentry/__init__.py +0 -0
- sycommon/sentry/sy_sentry.py +0 -35
- sycommon/synacos/nacos_client_base.py +0 -119
- sycommon/synacos/nacos_config_manager.py +0 -107
- sycommon/synacos/nacos_heartbeat_manager.py +0 -144
- sycommon/synacos/nacos_service_discovery.py +0 -157
- sycommon/synacos/nacos_service_registration.py +0 -270
- sycommon/tools/env.py +0 -62
- {sycommon_python_lib-0.1.56.dist-info → sycommon_python_lib-0.1.56b2.dist-info}/WHEEL +0 -0
- {sycommon_python_lib-0.1.56.dist-info → sycommon_python_lib-0.1.56b2.dist-info}/entry_points.txt +0 -0
- {sycommon_python_lib-0.1.56.dist-info → sycommon_python_lib-0.1.56b2.dist-info}/top_level.txt +0 -0
|
@@ -5,25 +5,16 @@ from aio_pika import connect_robust, RobustChannel, Message
|
|
|
5
5
|
from aio_pika.abc import (
|
|
6
6
|
AbstractRobustConnection, AbstractQueue, AbstractExchange, AbstractMessage
|
|
7
7
|
)
|
|
8
|
+
from aio_pika.exceptions import ChannelClosed
|
|
9
|
+
import aiormq.exceptions
|
|
10
|
+
|
|
8
11
|
from sycommon.logging.kafka_log import SYLogger
|
|
9
12
|
|
|
10
13
|
logger = SYLogger
|
|
11
14
|
|
|
12
15
|
|
|
13
|
-
class AsyncProperty:
|
|
14
|
-
"""实现 await obj.attr 的支持"""
|
|
15
|
-
|
|
16
|
-
def __init__(self, method):
|
|
17
|
-
self.method = method
|
|
18
|
-
|
|
19
|
-
def __get__(self, obj, objtype=None):
|
|
20
|
-
if obj is None:
|
|
21
|
-
return self
|
|
22
|
-
return self.method(obj)
|
|
23
|
-
|
|
24
|
-
|
|
25
16
|
class RabbitMQConnectionPool:
|
|
26
|
-
"""单连接单通道RabbitMQ
|
|
17
|
+
"""单连接单通道RabbitMQ客户端(核心特性:依赖connect_robust原生自动重连/恢复 + 仅关闭时释放资源)"""
|
|
27
18
|
|
|
28
19
|
def __init__(
|
|
29
20
|
self,
|
|
@@ -32,12 +23,13 @@ class RabbitMQConnectionPool:
|
|
|
32
23
|
username: str,
|
|
33
24
|
password: str,
|
|
34
25
|
virtualhost: str = "/",
|
|
35
|
-
heartbeat: int =
|
|
26
|
+
heartbeat: int = 30,
|
|
36
27
|
app_name: str = "",
|
|
37
|
-
connection_timeout: int =
|
|
28
|
+
connection_timeout: int = 30,
|
|
38
29
|
reconnect_interval: int = 5,
|
|
39
30
|
prefetch_count: int = 2,
|
|
40
31
|
):
|
|
32
|
+
# 基础配置校验与初始化
|
|
41
33
|
self.hosts = [host.strip() for host in hosts if host.strip()]
|
|
42
34
|
if not self.hosts:
|
|
43
35
|
raise ValueError("至少需要提供一个RabbitMQ主机地址")
|
|
@@ -52,347 +44,295 @@ class RabbitMQConnectionPool:
|
|
|
52
44
|
self.reconnect_interval = reconnect_interval
|
|
53
45
|
self.prefetch_count = prefetch_count
|
|
54
46
|
|
|
47
|
+
# 初始化时随机选择一个主机地址(固定使用,依赖原生重连)
|
|
55
48
|
self._current_host: str = random.choice(self.hosts)
|
|
56
|
-
logger.info(
|
|
49
|
+
logger.info(
|
|
50
|
+
f"随机选择RabbitMQ主机: {self._current_host}(依赖connect_robust原生自动重连/恢复)")
|
|
57
51
|
|
|
58
|
-
#
|
|
59
|
-
self._connection: Optional[AbstractRobustConnection] = None
|
|
60
|
-
self._channel: Optional[RobustChannel] = None
|
|
61
|
-
|
|
52
|
+
# 核心资源(单连接+单通道,基于原生自动重连)
|
|
53
|
+
self._connection: Optional[AbstractRobustConnection] = None # 原生自动重连连接
|
|
54
|
+
self._channel: Optional[RobustChannel] = None # 单通道(原生自动恢复)
|
|
55
|
+
# 消费者通道跟踪(独立于主通道)
|
|
56
|
+
self._consumer_channels: Dict[str,
|
|
57
|
+
Tuple[RobustChannel, Callable, bool, dict]] = {}
|
|
62
58
|
|
|
63
|
-
#
|
|
59
|
+
# 状态控制(并发安全+生命周期管理)
|
|
64
60
|
self._lock = asyncio.Lock()
|
|
65
61
|
self._initialized = False
|
|
66
62
|
self._is_shutdown = False
|
|
67
63
|
|
|
68
|
-
|
|
64
|
+
async def _is_connection_valid(self) -> bool:
|
|
65
|
+
"""原子化检查连接有效性(所有状态判断均加锁,确保原子性)"""
|
|
66
|
+
async with self._lock:
|
|
67
|
+
# 优先级:先判断是否关闭,再判断是否初始化,最后判断连接状态
|
|
68
|
+
return not self._is_shutdown and self._initialized and self._connection is not None and not self._connection.is_closed
|
|
69
|
+
|
|
70
|
+
@property
|
|
69
71
|
async def is_alive(self) -> bool:
|
|
70
|
-
"""
|
|
72
|
+
"""对外暴露的连接存活状态(原子化判断)"""
|
|
71
73
|
async with self._lock:
|
|
72
74
|
if self._is_shutdown:
|
|
73
75
|
return False
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
if self._connection is None or self._connection.is_closed:
|
|
77
|
-
return False
|
|
78
|
-
if self._channel is None or self._channel.is_closed:
|
|
79
|
-
return False
|
|
80
|
-
return True
|
|
81
|
-
|
|
82
|
-
async def _cleanup_resources(self):
|
|
83
|
-
"""
|
|
84
|
-
彻底清理旧资源
|
|
85
|
-
必须在持有 self._lock 的情况下调用
|
|
86
|
-
"""
|
|
87
|
-
logger.info("🧹 [CLEANUP] 开始清理旧资源...")
|
|
88
|
-
|
|
89
|
-
# 1. 清理所有消费者通道
|
|
90
|
-
if self._consumer_channels:
|
|
91
|
-
channels_to_close = list(self._consumer_channels.values())
|
|
92
|
-
self._consumer_channels.clear()
|
|
76
|
+
# 存活条件:未关闭 + 已初始化 + 连接有效 + 主通道有效
|
|
77
|
+
return self._initialized and self._connection is not None and not self._connection.is_closed and self._channel is not None and not self._channel.is_closed
|
|
93
78
|
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
logger.warning(f"⚠️ [CLEANUP_CH] 关闭消费者通道失败: {e}")
|
|
79
|
+
async def _create_connection(self) -> AbstractRobustConnection:
|
|
80
|
+
"""创建原生自动重连连接(仅创建一次,内部自动重试)"""
|
|
81
|
+
async with self._lock:
|
|
82
|
+
if self._is_shutdown:
|
|
83
|
+
raise RuntimeError("客户端已关闭,无法创建连接")
|
|
100
84
|
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
try:
|
|
104
|
-
if not self._channel.is_closed:
|
|
105
|
-
await self._channel.close()
|
|
106
|
-
except Exception as e:
|
|
107
|
-
logger.warning(f"⚠️ [CLEANUP_MAIN_CH] 关闭主通道失败: {e}")
|
|
108
|
-
finally:
|
|
109
|
-
self._channel = None
|
|
85
|
+
conn_url = f"amqp://{self.username}:{self.password}@{self._current_host}:{self.port}/{self.virtualhost}?name={self.app_name}&heartbeat={self.heartbeat}&reconnect_interval={self.reconnect_interval}&fail_fast=1"
|
|
86
|
+
logger.info(f"尝试创建原生自动重连连接: {self._current_host}:{self.port}")
|
|
110
87
|
|
|
111
|
-
# 3. 关闭连接
|
|
112
|
-
if self._connection:
|
|
113
|
-
try:
|
|
114
|
-
if not self._connection.is_closed:
|
|
115
|
-
# close() 可能是同步的,也可能是异步的,aio_pika 中通常是异步的
|
|
116
|
-
await self._connection.close()
|
|
117
|
-
except Exception as e:
|
|
118
|
-
logger.warning(f"⚠️ [CLEANUP_CONN] 关闭连接失败: {e}")
|
|
119
|
-
finally:
|
|
120
|
-
self._connection = None
|
|
121
|
-
|
|
122
|
-
logger.info("✅ [CLEANUP] 资源清理完成")
|
|
123
|
-
|
|
124
|
-
async def _create_connection_impl(self, host: str) -> AbstractRobustConnection:
|
|
125
|
-
conn_url = (
|
|
126
|
-
f"amqp://{self.username}:{self.password}@{host}:{self.port}/"
|
|
127
|
-
f"{self.virtualhost}?name={self.app_name}&heartbeat={self.heartbeat}"
|
|
128
|
-
f"&reconnect_interval={self.reconnect_interval}&fail_fast=1"
|
|
129
|
-
)
|
|
130
|
-
logger.info(f"🔌 [CONNECT] 尝试连接节点: {host}")
|
|
131
88
|
try:
|
|
132
|
-
conn = await
|
|
133
|
-
|
|
134
|
-
timeout=self.connection_timeout
|
|
89
|
+
conn = await connect_robust(
|
|
90
|
+
conn_url,
|
|
91
|
+
timeout=self.connection_timeout,
|
|
135
92
|
)
|
|
136
|
-
logger.info(f"
|
|
93
|
+
logger.info(f"连接创建成功: {self._current_host}:{self.port}(原生自动重连已启用)")
|
|
137
94
|
return conn
|
|
138
95
|
except Exception as e:
|
|
139
|
-
logger.error(f"
|
|
140
|
-
raise ConnectionError(
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
逻辑:
|
|
146
|
-
1. 检查连接状态
|
|
147
|
-
2. 如果断开 -> 清理 -> 轮询重试
|
|
148
|
-
3. 如果连接在但通道断开 -> 仅重建通道
|
|
149
|
-
"""
|
|
96
|
+
logger.error(f"连接创建失败: {str(e)}", exc_info=True)
|
|
97
|
+
raise ConnectionError(
|
|
98
|
+
f"无法连接RabbitMQ主机 {self._current_host}:{self.port}") from e
|
|
99
|
+
|
|
100
|
+
async def _init_single_channel(self):
|
|
101
|
+
"""初始化单通道(通道自带原生自动恢复)"""
|
|
150
102
|
async with self._lock:
|
|
103
|
+
# 先判断是否关闭(优先级最高)
|
|
151
104
|
if self._is_shutdown:
|
|
152
|
-
raise RuntimeError("
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
break
|
|
184
|
-
|
|
185
|
-
except Exception as e:
|
|
186
|
-
logger.warning(f"⚠️ [RECONNECT_RETRY] 节点 {host} 不可用")
|
|
187
|
-
if temp_conn is not None:
|
|
188
|
-
# 尝试连接失败了,必须把这个“半成品”连接关掉
|
|
189
|
-
try:
|
|
190
|
-
await temp_conn.close()
|
|
191
|
-
except Exception:
|
|
192
|
-
pass
|
|
193
|
-
last_error = e
|
|
194
|
-
await asyncio.sleep(self.reconnect_interval)
|
|
195
|
-
|
|
196
|
-
# 4. 如果所有尝试都失败
|
|
197
|
-
if last_error:
|
|
198
|
-
# 确保状态是干净的
|
|
199
|
-
self._connection = None
|
|
200
|
-
self._initialized = False
|
|
201
|
-
logger.error("💥 [RECONNECT_FATAL] 所有节点重试失败")
|
|
202
|
-
raise ConnectionError("所有 RabbitMQ 节点连接失败") from last_error
|
|
203
|
-
|
|
204
|
-
# --- 阶段B:通道恢复逻辑 (如果连接在但通道断了) ---
|
|
205
|
-
# 注意:这里不需要清理连接,只重置通道
|
|
206
|
-
if self._channel is None or self._channel.is_closed:
|
|
207
|
-
try:
|
|
208
|
-
self._channel = await self._connection.channel()
|
|
209
|
-
await self._channel.set_qos(prefetch_count=self.prefetch_count)
|
|
210
|
-
logger.info(f"✅ [CHANNEL_OK] 主通道已恢复")
|
|
211
|
-
except Exception as e:
|
|
212
|
-
# 如果连通道都创建不了,说明这个连接也是坏的,回滚到阶段A
|
|
213
|
-
logger.error(f"❌ [CHANNEL_FAIL] 通道创建失败,标记连接无效: {e}")
|
|
214
|
-
# 强制清理连接,触发下一次进入阶段A
|
|
215
|
-
await self._cleanup_resources()
|
|
216
|
-
raise
|
|
105
|
+
raise RuntimeError("客户端已关闭,无法初始化通道")
|
|
106
|
+
# 再判断连接是否有效
|
|
107
|
+
if not self._connection or self._connection.is_closed:
|
|
108
|
+
raise RuntimeError("无有效连接,无法初始化通道")
|
|
109
|
+
|
|
110
|
+
# 清理旧通道(如果存在)
|
|
111
|
+
if self._channel and not self._channel.is_closed:
|
|
112
|
+
await self._channel.close()
|
|
113
|
+
|
|
114
|
+
# 创建单通道并设置QOS
|
|
115
|
+
try:
|
|
116
|
+
self._channel = await self._connection.channel()
|
|
117
|
+
await self._channel.set_qos(prefetch_count=self.prefetch_count)
|
|
118
|
+
logger.info(f"单通道初始化完成(带原生自动恢复)")
|
|
119
|
+
except Exception as e:
|
|
120
|
+
logger.error(f"创建单通道失败: {str(e)}", exc_info=True)
|
|
121
|
+
raise
|
|
122
|
+
|
|
123
|
+
async def _check_and_recover_channel(self) -> RobustChannel:
|
|
124
|
+
"""检查并恢复通道(确保通道有效,所有状态判断加锁)"""
|
|
125
|
+
async with self._lock:
|
|
126
|
+
# 1. 先判断是否关闭(优先级最高)
|
|
127
|
+
if self._is_shutdown:
|
|
128
|
+
raise RuntimeError("客户端已关闭,无法获取通道")
|
|
129
|
+
# 2. 检查连接状态
|
|
130
|
+
if not self._connection or self._connection.is_closed:
|
|
131
|
+
raise RuntimeError("连接已关闭(等待原生重连)")
|
|
132
|
+
# 3. 通道失效时重新创建
|
|
133
|
+
if not self._channel or self._channel.is_closed:
|
|
134
|
+
logger.warning("通道失效,重新创建(依赖原生自动恢复)")
|
|
135
|
+
await self._init_single_channel()
|
|
217
136
|
|
|
218
137
|
return self._channel
|
|
219
138
|
|
|
220
139
|
async def init_pools(self):
|
|
221
|
-
"""
|
|
140
|
+
"""初始化客户端(仅执行一次)"""
|
|
222
141
|
async with self._lock:
|
|
142
|
+
# 原子化判断:是否已关闭/已初始化
|
|
223
143
|
if self._is_shutdown:
|
|
224
|
-
raise RuntimeError("
|
|
144
|
+
raise RuntimeError("客户端已关闭,无法初始化")
|
|
225
145
|
if self._initialized:
|
|
146
|
+
logger.warning("客户端已初始化,无需重复调用")
|
|
226
147
|
return
|
|
227
148
|
|
|
228
|
-
# 在 try 之前声明变量,确保 except 块能访问
|
|
229
|
-
conn_created_in_this_try = None
|
|
230
|
-
|
|
231
149
|
try:
|
|
232
|
-
#
|
|
233
|
-
|
|
234
|
-
conn = await self._create_connection_impl(init_host)
|
|
150
|
+
# 1. 创建原生自动重连连接
|
|
151
|
+
self._connection = await self._create_connection()
|
|
235
152
|
|
|
236
|
-
#
|
|
237
|
-
|
|
153
|
+
# 2. 初始化单通道
|
|
154
|
+
await self._init_single_channel()
|
|
238
155
|
|
|
156
|
+
# 3. 标记为已初始化(加锁保护)
|
|
239
157
|
async with self._lock:
|
|
240
|
-
if self._is_shutdown:
|
|
241
|
-
raise RuntimeError("客户端已关闭")
|
|
242
|
-
|
|
243
|
-
# 提交新资源
|
|
244
|
-
self._connection = conn
|
|
245
|
-
self._channel = await self._connection.channel()
|
|
246
|
-
await self._channel.set_qos(prefetch_count=self.prefetch_count)
|
|
247
158
|
self._initialized = True
|
|
248
159
|
|
|
249
|
-
|
|
250
|
-
conn_created_in_this_try = None
|
|
251
|
-
|
|
252
|
-
logger.info(f"🚀 [INIT_OK] 连接池初始化完成: {init_host}")
|
|
253
|
-
|
|
160
|
+
logger.info("RabbitMQ单通道客户端初始化完成(原生自动重连/恢复已启用)")
|
|
254
161
|
except Exception as e:
|
|
255
|
-
logger.error(f"
|
|
256
|
-
|
|
257
|
-
# 这里现在可以合法访问 conn_created_in_this_try
|
|
258
|
-
if conn_created_in_this_try is not None:
|
|
259
|
-
try:
|
|
260
|
-
await conn_created_in_this_try.close()
|
|
261
|
-
except Exception:
|
|
262
|
-
pass
|
|
263
|
-
|
|
264
|
-
if not self._is_shutdown:
|
|
265
|
-
await self.close()
|
|
162
|
+
logger.error(f"初始化失败: {str(e)}", exc_info=True)
|
|
163
|
+
await self.close() # 初始化失败直接关闭
|
|
266
164
|
raise
|
|
267
165
|
|
|
268
|
-
async def
|
|
269
|
-
"""
|
|
270
|
-
强制重连
|
|
271
|
-
严格执行:清理所有资源 -> 尝试建立新资源
|
|
272
|
-
"""
|
|
166
|
+
async def acquire_channel(self) -> Tuple[RobustChannel, AbstractRobustConnection]:
|
|
167
|
+
"""获取单通道(返回 (通道, 连接) 元组,保持API兼容)"""
|
|
273
168
|
async with self._lock:
|
|
169
|
+
# 原子化状态校验
|
|
274
170
|
if self._is_shutdown:
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
# 1. 【关键】标记未初始化,迫使 _ensure_main_channel 走清理流程
|
|
280
|
-
self._initialized = False
|
|
281
|
-
|
|
282
|
-
# 2. 【关键】立即清理旧资源 (在锁内)
|
|
283
|
-
await self._cleanup_resources()
|
|
171
|
+
raise RuntimeError("客户端已关闭,无法获取通道")
|
|
172
|
+
if not self._initialized:
|
|
173
|
+
raise RuntimeError("客户端未初始化,请先调用init_pools()")
|
|
284
174
|
|
|
285
|
-
|
|
175
|
+
# 检查并恢复通道
|
|
176
|
+
channel = await self._check_and_recover_channel()
|
|
177
|
+
return channel, self._connection # 单通道无需管理"使用中/空闲"状态
|
|
286
178
|
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
except Exception as e:
|
|
292
|
-
logger.error(f"❌ [FORCE_RECONNECT_FAIL] 强制重连失败: {e}")
|
|
293
|
-
raise
|
|
179
|
+
async def declare_queue(self, queue_name: str, **kwargs) -> AbstractQueue:
|
|
180
|
+
"""声明队列(使用单通道)"""
|
|
181
|
+
channel, _ = await self.acquire_channel()
|
|
182
|
+
return await channel.declare_queue(queue_name, **kwargs)
|
|
294
183
|
|
|
295
|
-
async def
|
|
296
|
-
"""
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
return await self._ensure_main_channel(), self._connection
|
|
184
|
+
async def declare_exchange(self, exchange_name: str, exchange_type: str = "direct", **kwargs) -> AbstractExchange:
|
|
185
|
+
"""声明交换机(使用单通道)"""
|
|
186
|
+
channel, _ = await self.acquire_channel()
|
|
187
|
+
return await channel.declare_exchange(exchange_name, exchange_type, **kwargs)
|
|
300
188
|
|
|
301
189
|
async def publish_message(self, routing_key: str, message_body: bytes, exchange_name: str = "", **kwargs):
|
|
190
|
+
"""发布消息(依赖原生自动重连/恢复)"""
|
|
302
191
|
channel, _ = await self.acquire_channel()
|
|
303
192
|
try:
|
|
304
193
|
exchange = channel.default_exchange if not exchange_name else await channel.get_exchange(exchange_name)
|
|
305
194
|
message = Message(body=message_body, **kwargs)
|
|
306
195
|
await exchange.publish(message, routing_key=routing_key)
|
|
196
|
+
logger.debug(
|
|
197
|
+
f"消息发布成功 - 交换机: {exchange.name}, 路由键: {routing_key}"
|
|
198
|
+
)
|
|
307
199
|
except Exception as e:
|
|
308
|
-
logger.error(f"
|
|
309
|
-
raise
|
|
200
|
+
logger.error(f"发布消息失败: {str(e)}", exc_info=True)
|
|
201
|
+
raise # 原生会自动重连,无需手动处理
|
|
310
202
|
|
|
311
203
|
async def consume_queue(self, queue_name: str, callback: Callable[[AbstractMessage], asyncio.Future], auto_ack: bool = False, **kwargs):
|
|
312
|
-
|
|
313
|
-
await self.init_pools()
|
|
314
|
-
|
|
315
|
-
# 检查是否已存在
|
|
204
|
+
"""消费队列(独立通道,带原生自动恢复)"""
|
|
316
205
|
async with self._lock:
|
|
206
|
+
# 原子化状态校验
|
|
317
207
|
if self._is_shutdown:
|
|
318
|
-
raise RuntimeError("
|
|
208
|
+
raise RuntimeError("客户端已关闭,无法启动消费")
|
|
209
|
+
if not self._initialized:
|
|
210
|
+
raise RuntimeError("客户端未初始化,请先调用init_pools()")
|
|
319
211
|
if queue_name in self._consumer_channels:
|
|
320
|
-
logger.warning(f"
|
|
212
|
+
logger.warning(f"队列 {queue_name} 已在消费中,无需重复启动")
|
|
321
213
|
return
|
|
322
|
-
if not self._connection or self._connection.is_closed:
|
|
323
|
-
raise RuntimeError("连接不可用,无法启动消费")
|
|
324
214
|
|
|
325
|
-
#
|
|
215
|
+
# 先声明队列(确保队列存在)
|
|
326
216
|
await self.declare_queue(queue_name, **kwargs)
|
|
327
217
|
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
218
|
+
# 创建独立的消费者通道(不使用主单通道,避免消费阻塞发布)
|
|
219
|
+
async with self._lock:
|
|
220
|
+
if self._is_shutdown: # 二次校验:防止创建通道前客户端被关闭
|
|
221
|
+
raise RuntimeError("客户端已关闭,无法创建消费者通道")
|
|
222
|
+
if not self._connection or self._connection.is_closed:
|
|
223
|
+
raise RuntimeError("无有效连接,无法创建消费者通道")
|
|
224
|
+
channel = await self._connection.channel()
|
|
225
|
+
await channel.set_qos(prefetch_count=self.prefetch_count)
|
|
331
226
|
|
|
332
|
-
#
|
|
333
|
-
|
|
334
|
-
|
|
227
|
+
# 注册消费者通道
|
|
228
|
+
self._consumer_channels[queue_name] = (
|
|
229
|
+
channel, callback, auto_ack, kwargs)
|
|
335
230
|
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
231
|
+
async def consume_callback_wrapper(message: AbstractMessage):
|
|
232
|
+
"""消费回调包装(处理通道失效,依赖原生恢复)"""
|
|
233
|
+
try:
|
|
234
|
+
async with self._lock:
|
|
235
|
+
# 原子化校验状态:客户端是否关闭 + 通道是否有效 + 连接是否有效
|
|
236
|
+
if self._is_shutdown:
|
|
237
|
+
logger.warning(f"客户端已关闭,拒绝处理消息(队列: {queue_name})")
|
|
238
|
+
if not auto_ack:
|
|
239
|
+
await message.nack(requeue=True)
|
|
240
|
+
return
|
|
241
|
+
channel_valid = not channel.is_closed
|
|
242
|
+
conn_valid = self._connection and not self._connection.is_closed
|
|
243
|
+
|
|
244
|
+
if not channel_valid or not conn_valid:
|
|
245
|
+
logger.warning(f"消费者通道 {queue_name} 失效(等待原生自动恢复)")
|
|
246
|
+
if not auto_ack:
|
|
247
|
+
await message.nack(requeue=True)
|
|
343
248
|
return
|
|
344
249
|
|
|
345
|
-
|
|
250
|
+
# 执行业务回调
|
|
251
|
+
await callback(message)
|
|
252
|
+
if not auto_ack:
|
|
253
|
+
await message.ack()
|
|
254
|
+
except ChannelClosed as e:
|
|
255
|
+
logger.error(f"消费者通道 {queue_name} 关闭: {str(e)}", exc_info=True)
|
|
256
|
+
if not auto_ack:
|
|
257
|
+
await message.nack(requeue=True)
|
|
258
|
+
except aiormq.exceptions.ChannelInvalidStateError as e:
|
|
259
|
+
logger.error(
|
|
260
|
+
f"消费者通道 {queue_name} 状态异常: {str(e)}", exc_info=True)
|
|
261
|
+
if not auto_ack:
|
|
262
|
+
await message.nack(requeue=True)
|
|
263
|
+
except Exception as e:
|
|
264
|
+
logger.error(
|
|
265
|
+
f"消费消息失败(队列: {queue_name}): {str(e)}", exc_info=True)
|
|
266
|
+
if not auto_ack:
|
|
267
|
+
await message.nack(requeue=True)
|
|
346
268
|
|
|
347
|
-
|
|
348
|
-
try:
|
|
349
|
-
await callback(message)
|
|
350
|
-
if not auto_ack:
|
|
351
|
-
await message.ack()
|
|
352
|
-
except Exception as e:
|
|
353
|
-
logger.error(f"❌ [CALLBACK_ERR] {queue_name}: {e}")
|
|
354
|
-
if not auto_ack:
|
|
355
|
-
await message.nack(requeue=True)
|
|
269
|
+
logger.info(f"开始消费队列: {queue_name}(通道带原生自动恢复)")
|
|
356
270
|
|
|
357
|
-
|
|
358
|
-
|
|
271
|
+
try:
|
|
272
|
+
await channel.basic_consume(
|
|
273
|
+
queue_name,
|
|
274
|
+
consumer_callback=consume_callback_wrapper,
|
|
275
|
+
auto_ack=auto_ack,
|
|
276
|
+
**kwargs
|
|
359
277
|
)
|
|
360
|
-
logger.info(f"🎧 [CONSUME_START] {queue_name}")
|
|
361
|
-
|
|
362
278
|
except Exception as e:
|
|
363
|
-
logger.error(f"
|
|
364
|
-
#
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
if
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
pass
|
|
279
|
+
logger.error(f"启动消费失败(队列: {queue_name}): {str(e)}", exc_info=True)
|
|
280
|
+
# 清理异常资源
|
|
281
|
+
try:
|
|
282
|
+
async with self._lock:
|
|
283
|
+
if not channel.is_closed:
|
|
284
|
+
await channel.close()
|
|
285
|
+
# 移除无效的消费者通道注册
|
|
286
|
+
if queue_name in self._consumer_channels:
|
|
287
|
+
del self._consumer_channels[queue_name]
|
|
288
|
+
except Exception as close_e:
|
|
289
|
+
logger.warning(f"关闭消费者通道失败: {str(close_e)}")
|
|
375
290
|
raise
|
|
376
291
|
|
|
377
292
|
async def close(self):
|
|
378
|
-
"""
|
|
293
|
+
"""关闭客户端(释放所有资源,原子化状态管理)"""
|
|
379
294
|
async with self._lock:
|
|
380
295
|
if self._is_shutdown:
|
|
296
|
+
logger.warning("客户端已关闭,无需重复操作")
|
|
381
297
|
return
|
|
298
|
+
# 先标记为关闭,阻止后续所有操作(原子化修改)
|
|
382
299
|
self._is_shutdown = True
|
|
383
300
|
self._initialized = False
|
|
384
301
|
|
|
385
|
-
logger.info("
|
|
302
|
+
logger.info("开始关闭RabbitMQ单通道客户端(释放所有资源)...")
|
|
386
303
|
|
|
387
|
-
# 1.
|
|
388
|
-
|
|
304
|
+
# 1. 关闭所有消费者通道
|
|
305
|
+
consumer_channels = []
|
|
306
|
+
async with self._lock:
|
|
307
|
+
consumer_channels = list(self._consumer_channels.values())
|
|
308
|
+
self._consumer_channels.clear()
|
|
309
|
+
for channel, _, _, _ in consumer_channels:
|
|
310
|
+
try:
|
|
311
|
+
if not channel.is_closed:
|
|
312
|
+
await channel.close()
|
|
313
|
+
except Exception as e:
|
|
314
|
+
logger.warning(f"关闭消费者通道失败: {str(e)}")
|
|
389
315
|
|
|
390
|
-
|
|
316
|
+
# 2. 关闭主单通道
|
|
317
|
+
if self._channel:
|
|
318
|
+
try:
|
|
319
|
+
async with self._lock:
|
|
320
|
+
if not self._channel.is_closed:
|
|
321
|
+
await self._channel.close()
|
|
322
|
+
except Exception as e:
|
|
323
|
+
logger.warning(f"关闭主通道失败: {str(e)}")
|
|
324
|
+
self._channel = None
|
|
391
325
|
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
326
|
+
# 3. 关闭连接(终止原生自动重连)
|
|
327
|
+
if self._connection:
|
|
328
|
+
try:
|
|
329
|
+
async with self._lock:
|
|
330
|
+
if not self._connection.is_closed:
|
|
331
|
+
await self._connection.close()
|
|
332
|
+
logger.info(
|
|
333
|
+
f"已关闭连接: {self._current_host}:{self.port}(终止原生自动重连)")
|
|
334
|
+
except Exception as e:
|
|
335
|
+
logger.warning(f"关闭连接失败: {str(e)}")
|
|
336
|
+
self._connection = None
|
|
395
337
|
|
|
396
|
-
|
|
397
|
-
channel, _ = await self.acquire_channel()
|
|
398
|
-
return await channel.declare_exchange(exchange_name, exchange_type, **kwargs)
|
|
338
|
+
logger.info("RabbitMQ单通道客户端已完全关闭")
|