sycommon-python-lib 0.1.46__py3-none-any.whl → 0.1.57b1__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.
Files changed (51) hide show
  1. sycommon/config/Config.py +29 -4
  2. sycommon/config/LangfuseConfig.py +15 -0
  3. sycommon/config/RerankerConfig.py +1 -0
  4. sycommon/config/SentryConfig.py +13 -0
  5. sycommon/database/async_base_db_service.py +36 -0
  6. sycommon/database/async_database_service.py +96 -0
  7. sycommon/llm/__init__.py +0 -0
  8. sycommon/llm/embedding.py +204 -0
  9. sycommon/llm/get_llm.py +37 -0
  10. sycommon/llm/llm_logger.py +126 -0
  11. sycommon/llm/llm_tokens.py +119 -0
  12. sycommon/llm/struct_token.py +192 -0
  13. sycommon/llm/sy_langfuse.py +103 -0
  14. sycommon/llm/usage_token.py +117 -0
  15. sycommon/logging/async_sql_logger.py +65 -0
  16. sycommon/logging/kafka_log.py +200 -434
  17. sycommon/logging/logger_levels.py +23 -0
  18. sycommon/middleware/context.py +2 -0
  19. sycommon/middleware/exception.py +10 -16
  20. sycommon/middleware/timeout.py +2 -1
  21. sycommon/middleware/traceid.py +179 -51
  22. sycommon/notice/__init__.py +0 -0
  23. sycommon/notice/uvicorn_monitor.py +200 -0
  24. sycommon/rabbitmq/rabbitmq_client.py +267 -290
  25. sycommon/rabbitmq/rabbitmq_pool.py +277 -465
  26. sycommon/rabbitmq/rabbitmq_service.py +23 -891
  27. sycommon/rabbitmq/rabbitmq_service_client_manager.py +211 -0
  28. sycommon/rabbitmq/rabbitmq_service_connection_monitor.py +73 -0
  29. sycommon/rabbitmq/rabbitmq_service_consumer_manager.py +285 -0
  30. sycommon/rabbitmq/rabbitmq_service_core.py +117 -0
  31. sycommon/rabbitmq/rabbitmq_service_producer_manager.py +238 -0
  32. sycommon/sentry/__init__.py +0 -0
  33. sycommon/sentry/sy_sentry.py +35 -0
  34. sycommon/services.py +144 -115
  35. sycommon/synacos/feign.py +18 -7
  36. sycommon/synacos/feign_client.py +26 -8
  37. sycommon/synacos/nacos_client_base.py +119 -0
  38. sycommon/synacos/nacos_config_manager.py +107 -0
  39. sycommon/synacos/nacos_heartbeat_manager.py +144 -0
  40. sycommon/synacos/nacos_service.py +65 -769
  41. sycommon/synacos/nacos_service_discovery.py +157 -0
  42. sycommon/synacos/nacos_service_registration.py +270 -0
  43. sycommon/tools/env.py +62 -0
  44. sycommon/tools/merge_headers.py +117 -0
  45. sycommon/tools/snowflake.py +238 -23
  46. {sycommon_python_lib-0.1.46.dist-info → sycommon_python_lib-0.1.57b1.dist-info}/METADATA +18 -11
  47. sycommon_python_lib-0.1.57b1.dist-info/RECORD +89 -0
  48. sycommon_python_lib-0.1.46.dist-info/RECORD +0 -59
  49. {sycommon_python_lib-0.1.46.dist-info → sycommon_python_lib-0.1.57b1.dist-info}/WHEEL +0 -0
  50. {sycommon_python_lib-0.1.46.dist-info → sycommon_python_lib-0.1.57b1.dist-info}/entry_points.txt +0 -0
  51. {sycommon_python_lib-0.1.46.dist-info → sycommon_python_lib-0.1.57b1.dist-info}/top_level.txt +0 -0
@@ -1,872 +1,38 @@
1
+ from typing import Type
1
2
  import asyncio
2
- import json
3
- from typing import (
4
- Callable, Coroutine, Dict, List, Optional, Type, Union, Any, Set
5
- )
6
- from pydantic import BaseModel
7
- from aio_pika.abc import AbstractIncomingMessage, ConsumerTag
8
-
9
- from sycommon.models.mqmsg_model import MQMsgModel
10
- from sycommon.models.mqlistener_config import RabbitMQListenerConfig
11
- from sycommon.models.mqsend_config import RabbitMQSendConfig
12
- from sycommon.models.sso_user import SsoUser
13
3
  from sycommon.logging.kafka_log import SYLogger
14
- from sycommon.rabbitmq.rabbitmq_client import RabbitMQClient, RabbitMQConnectionPool
4
+ from sycommon.rabbitmq.rabbitmq_service_connection_monitor import RabbitMQConnectionMonitor
5
+ from sycommon.rabbitmq.rabbitmq_service_consumer_manager import RabbitMQConsumerManager
6
+ from sycommon.rabbitmq.rabbitmq_service_producer_manager import RabbitMQProducerManager
15
7
 
16
8
  logger = SYLogger
17
9
 
18
10
 
19
- class RabbitMQService:
11
+ class RabbitMQService(RabbitMQConnectionMonitor, RabbitMQProducerManager, RabbitMQConsumerManager):
20
12
  """
21
- RabbitMQ服务封装,管理多个客户端实例,基于连接池实现资源复用
22
- 适配细粒度锁设计的RabbitMQClient,确保线程安全+高可用
13
+ RabbitMQ服务对外统一接口 - 保持原有API兼容
23
14
  """
24
-
25
- # 保存多个客户端实例
26
- _clients: Dict[str, RabbitMQClient] = {}
27
- # 保存消息处理器
28
- _message_handlers: Dict[str, Callable[[
29
- MQMsgModel, AbstractIncomingMessage], Coroutine[Any, Any, None]]] = {}
30
- # 保存消费者任务
31
- _consumer_tasks: Dict[str, asyncio.Task] = {}
32
- # 保存配置信息
33
- _config: Optional[dict] = None
34
- # 存储发送客户端的名称
35
- _sender_client_names: List[str] = []
36
- # 用于控制消费者任务退出的事件
37
- _consumer_events: Dict[str, asyncio.Event] = {}
38
- # 存储消费者标签
39
- _consumer_tags: Dict[str, ConsumerTag] = {}
40
- # 跟踪已初始化的队列
41
- _initialized_queues: Set[str] = set()
42
- # 异步锁,确保初始化安全
43
- _init_locks: Dict[str, asyncio.Lock] = {}
44
- # 标记是否有监听器和发送器
45
- _has_listeners: bool = False
46
- _has_senders: bool = False
47
- # 消费启动超时设置
48
- CONSUMER_START_TIMEOUT = 30 # 30秒超时
49
- # 连接池实例
50
- _connection_pool: Optional[RabbitMQConnectionPool] = None
51
- # 服务关闭标记
52
- _is_shutdown: bool = False
53
- # 服务关闭锁
54
- _shutdown_lock = asyncio.Lock()
55
- # 连接状态监控任务
56
- _connection_monitor_task: Optional[asyncio.Task] = None
57
- # 重连配置
58
- RECONNECT_INTERVAL = 15 # 重连基础间隔(秒)
59
- MAX_RECONNECT_ATTEMPTS = 10 # 最大连续重连次数
60
-
61
15
  @classmethod
62
16
  def init(cls, config: dict, has_listeners: bool = False, has_senders: bool = False) -> Type['RabbitMQService']:
63
- """初始化RabbitMQ服务(支持集群配置),同时创建连接池"""
64
- from sycommon.synacos.nacos_service import NacosService
65
-
66
- # 防止重复初始化
67
- if cls._config:
68
- logger.warning("RabbitMQService已初始化,无需重复调用")
69
- return cls
70
-
71
- # 获取MQ配置
72
- cls._config = NacosService(config).share_configs.get(
73
- "mq.yml", {}).get('spring', {}).get('rabbitmq', {})
74
- cls._config["APP_NAME"] = config.get("Name", "")
17
+ """初始化RabbitMQ服务(保持原有接口)"""
18
+ # 初始化配置
19
+ cls.init_config(config)
75
20
 
76
- # 打印关键配置信息(显示所有集群节点)
77
- logger.info(
78
- f"RabbitMQ服务初始化 - 集群节点: {cls._config.get('host')}, "
79
- f"端口: {cls._config.get('port')}, "
80
- f"虚拟主机: {cls._config.get('virtual-host')}, "
81
- f"应用名: {cls._config.get('APP_NAME')}, "
82
- f"心跳: {cls._config.get('heartbeat', 30)}s"
83
- )
21
+ # 设置模式标记
22
+ cls.set_mode_flags(has_listeners=has_listeners,
23
+ has_senders=has_senders)
84
24
 
85
- # 保存发送器和监听器存在状态
86
- cls._has_listeners = has_listeners
87
- cls._has_senders = has_senders
88
- cls._is_shutdown = False
25
+ # 初始化连接池
26
+ asyncio.create_task(cls.init_connection_pool())
89
27
 
90
- # 初始化连接池(在单独的异步方法中启动)
91
- asyncio.create_task(cls._init_connection_pool())
92
-
93
- # 启动连接监控任务(监听连接状态,自动重连)
94
- cls._connection_monitor_task = asyncio.create_task(
95
- cls._monitor_connections())
28
+ # 启动连接监控
29
+ cls.start_connection_monitor()
96
30
 
97
31
  return cls
98
32
 
99
- @classmethod
100
- async def _init_connection_pool(cls):
101
- """初始化连接池(异步操作,带重试)"""
102
- if cls._connection_pool or not cls._config or cls._is_shutdown:
103
- return
104
-
105
- try:
106
- # 解析集群节点
107
- hosts_str = cls._config.get('host', "")
108
- hosts_list = [host.strip()
109
- for host in hosts_str.split(',') if host.strip()]
110
- if not hosts_list:
111
- raise ValueError("RabbitMQ集群配置为空,请检查host参数")
112
-
113
- global_prefetch_count = cls._config.get('prefetch_count', 2)
114
-
115
- # 创建连接池
116
- cls._connection_pool = RabbitMQConnectionPool(
117
- hosts=hosts_list,
118
- port=cls._config.get('port', 5672),
119
- username=cls._config.get('username', ""),
120
- password=cls._config.get('password', ""),
121
- virtualhost=cls._config.get('virtual-host', "/"),
122
- app_name=cls._config.get("APP_NAME", ""),
123
- prefetch_count=global_prefetch_count,
124
- )
125
-
126
- # 初始化连接池
127
- await asyncio.wait_for(cls._connection_pool.init_pools(), timeout=30)
128
- logger.info("RabbitMQ连接池初始化成功")
129
-
130
- except Exception as e:
131
- logger.error(f"RabbitMQ连接池初始化失败: {str(e)}", exc_info=True)
132
- # 连接池初始化失败时重试(未关闭状态下)
133
- if not cls._is_shutdown:
134
- await asyncio.sleep(cls.RECONNECT_INTERVAL)
135
- asyncio.create_task(cls._init_connection_pool())
136
-
137
- @classmethod
138
- async def _monitor_connections(cls):
139
- """连接监控任务:定期检查所有客户端连接状态,自动重连"""
140
- logger.info("RabbitMQ连接监控任务启动")
141
- while not cls._is_shutdown:
142
- try:
143
- await asyncio.sleep(cls.RECONNECT_INTERVAL) # 固定15秒间隔
144
-
145
- # 跳过未初始化的连接池
146
- if not cls._connection_pool or not cls._connection_pool._initialized:
147
- continue
148
-
149
- # 检查所有客户端连接
150
- # 使用list避免迭代中修改
151
- for client_name, client in list(cls._clients.items()):
152
- try:
153
- # 双重校验连接状态(客户端内部校验 + 连接池连接校验)
154
- client_connected = await client.is_connected
155
- conn_connected = not (
156
- client._channel_conn and client._channel_conn.is_closed)
157
-
158
- if not client_connected or not conn_connected:
159
- logger.warning(
160
- f"客户端 '{client_name}' 连接异常 - 客户端状态: {client_connected}, "
161
- f"连接状态: {conn_connected},触发自动重连"
162
- )
163
-
164
- # 重连前先清理无效资源
165
- await cls._clean_client_resources(client)
166
-
167
- # 执行重连(带重试)
168
- reconnect_success = await cls._reconnect_client(client_name, client)
169
- if reconnect_success:
170
- logger.info(f"客户端 '{client_name}' 重连成功")
171
- else:
172
- logger.error(f"客户端 '{client_name}' 重连失败,将继续监控")
173
-
174
- except Exception as e:
175
- logger.error(
176
- f"监控客户端 '{client_name}' 连接状态失败: {str(e)}", exc_info=True)
177
-
178
- # 检查连接池状态(如果连接池已关闭,重新初始化)
179
- if not await cls._connection_pool.is_alive:
180
- logger.error("RabbitMQ连接池已关闭,尝试重新初始化")
181
- asyncio.create_task(cls._init_connection_pool())
182
-
183
- except Exception as e:
184
- logger.error("RabbitMQ连接监控任务异常", exc_info=True)
185
- await asyncio.sleep(cls.RECONNECT_INTERVAL) # 异常后延迟重启监控
186
-
187
- logger.info("RabbitMQ连接监控任务停止")
188
-
189
- @classmethod
190
- async def _clean_client_resources(cls, client: RabbitMQClient):
191
- """清理客户端无效资源(通道+连接)"""
192
- try:
193
- if client._channel and client._channel_conn:
194
- # 先停止消费(避免消费中释放资源)
195
- if client._consumer_tag:
196
- await client.stop_consuming()
197
- # 释放通道到连接池
198
- await cls._connection_pool.release_channel(client._channel, client._channel_conn)
199
- logger.debug("客户端无效资源释放成功")
200
- except Exception as e:
201
- logger.warning(f"释放客户端无效资源失败: {str(e)}")
202
- finally:
203
- # 强制重置客户端状态
204
- client._channel = None
205
- client._channel_conn = None
206
- client._exchange = None
207
- client._queue = None
208
- client._consumer_tag = None
209
-
210
- @classmethod
211
- async def _reconnect_client(cls, client_name: str, client: RabbitMQClient) -> bool:
212
- """客户端重连(带重试机制)"""
213
- # 重连冷却,避免任务堆积
214
- cooldown = cls.RECONNECT_INTERVAL * 2
215
- await asyncio.sleep(cooldown)
216
-
217
- for attempt in range(cls.MAX_RECONNECT_ATTEMPTS):
218
- try:
219
- # 执行重连
220
- await client.connect()
221
-
222
- # 验证重连结果(双重校验)
223
- if await client.is_connected and client._queue:
224
- # 如果是消费者,重新启动消费
225
- if client_name in cls._message_handlers:
226
- # 先停止旧的消费任务
227
- if client_name in cls._consumer_tasks:
228
- old_task = cls._consumer_tasks[client_name]
229
- if not old_task.done():
230
- old_task.cancel()
231
- try:
232
- await asyncio.wait_for(old_task, timeout=5)
233
- except:
234
- pass
235
- # 启动新的消费任务
236
- await cls.start_consumer(client_name)
237
- return True
238
- else:
239
- logger.warning(
240
- f"客户端 '{client_name}' 重连尝试 {attempt+1} 失败:资源未完全初始化")
241
- except Exception as e:
242
- logger.error(
243
- f"客户端 '{client_name}' 重连尝试 {attempt+1} 失败: {str(e)}", exc_info=True)
244
-
245
- await asyncio.sleep(cls.RECONNECT_INTERVAL)
246
-
247
- if not cls._is_shutdown:
248
- asyncio.create_task(cls._reconnect_client(client_name, client))
249
- return False
250
-
251
- @classmethod
252
- async def _create_client(cls, queue_name: str, **kwargs) -> RabbitMQClient:
253
- """创建客户端实例(适配新的RabbitMQClient API)"""
254
- if cls._is_shutdown:
255
- raise RuntimeError("RabbitMQService已关闭,无法创建客户端")
256
-
257
- if not cls._connection_pool or not cls._connection_pool._initialized:
258
- # 等待连接池初始化
259
- start_time = asyncio.get_event_loop().time()
260
- while not (cls._connection_pool and cls._connection_pool._initialized) and not cls._is_shutdown:
261
- if asyncio.get_event_loop().time() - start_time > 30:
262
- raise TimeoutError("等待连接池初始化超时")
263
- await asyncio.sleep(1)
264
- if cls._is_shutdown:
265
- raise RuntimeError("服务关闭中,取消创建客户端")
266
-
267
- app_name = kwargs.get('app_name', cls._config.get(
268
- "APP_NAME", "")) if cls._config else ""
269
- is_sender = not cls._has_listeners
270
-
271
- # 根据组件类型决定是否允许创建队列
272
- create_if_not_exists = cls._has_listeners # 只有监听器允许创建队列
273
-
274
- # 为监听器队列名称拼接应用名
275
- processed_queue_name = queue_name
276
- if create_if_not_exists and not is_sender and processed_queue_name and app_name:
277
- if not processed_queue_name.endswith(f".{app_name}"):
278
- processed_queue_name = f"{processed_queue_name}.{app_name}"
279
- logger.info(f"监听器队列名称自动拼接app-name: {processed_queue_name}")
280
- else:
281
- logger.info(f"监听器队列已包含app-name: {processed_queue_name}")
282
-
283
- logger.info(
284
- f"创建客户端 - 队列: {processed_queue_name}, 发送器: {is_sender}, "
285
- f"允许创建: {create_if_not_exists}"
286
- )
287
-
288
- # 创建客户端实例(适配新的RabbitMQClient参数)
289
- client = RabbitMQClient(
290
- connection_pool=cls._connection_pool,
291
- exchange_name=cls._config.get(
292
- 'exchange_name', "system.topic.exchange"),
293
- exchange_type=kwargs.get('exchange_type', "topic"),
294
- queue_name=processed_queue_name,
295
- routing_key=kwargs.get(
296
- 'routing_key', f"{processed_queue_name.split('.')[0]}.#" if processed_queue_name else "#"),
297
- durable=kwargs.get('durable', True),
298
- auto_delete=kwargs.get('auto_delete', False),
299
- auto_parse_json=kwargs.get('auto_parse_json', True),
300
- create_if_not_exists=create_if_not_exists,
301
- prefetch_count=kwargs.get('prefetch_count', 2),
302
- )
303
-
304
- # 连接客户端
305
- await client.connect()
306
-
307
- # 监听器客户端连接后延迟1秒,确保消费状态就绪(仅首次启动)
308
- if not is_sender and create_if_not_exists:
309
- logger.info(
310
- f"监听器客户端 '{processed_queue_name}' 连接成功,延迟1秒启动消费(解决启动时序问题)")
311
- await asyncio.sleep(1)
312
-
313
- return client
314
-
315
- @classmethod
316
- async def get_client(
317
- cls,
318
- client_name: str = "default", **kwargs
319
- ) -> RabbitMQClient:
320
- """获取或创建RabbitMQ客户端(基于连接池,线程安全)"""
321
- if cls._is_shutdown:
322
- raise RuntimeError("RabbitMQService已关闭,无法获取客户端")
323
-
324
- if not cls._config:
325
- raise ValueError("RabbitMQService尚未初始化,请先调用init方法")
326
-
327
- # 等待连接池就绪
328
- if not cls._connection_pool or not cls._connection_pool._initialized:
329
- start_time = asyncio.get_event_loop().time()
330
- while not (cls._connection_pool and cls._connection_pool._initialized) and not cls._is_shutdown:
331
- if asyncio.get_event_loop().time() - start_time > 30:
332
- raise TimeoutError("等待连接池初始化超时")
333
- await asyncio.sleep(1)
334
- if cls._is_shutdown:
335
- raise RuntimeError("服务关闭中,取消获取客户端")
336
-
337
- # 确保锁存在
338
- if client_name not in cls._init_locks:
339
- cls._init_locks[client_name] = asyncio.Lock()
340
-
341
- async with cls._init_locks[client_name]:
342
- # 如果客户端已存在且连接有效,直接返回
343
- if client_name in cls._clients:
344
- client = cls._clients[client_name]
345
- is_sender = not cls._has_listeners or (
346
- not kwargs.get('create_if_not_exists', True))
347
-
348
- if await client.is_connected:
349
- # 如果是监听器但队列未初始化,重新连接
350
- if not is_sender and not client._queue:
351
- logger.info(f"客户端 '{client_name}' 队列未初始化,重新连接")
352
- client.create_if_not_exists = True
353
- await client.connect()
354
- return client
355
- else:
356
- logger.info(f"客户端 '{client_name}' 连接已关闭,重新连接")
357
- if not is_sender:
358
- client.create_if_not_exists = True
359
- await client.connect()
360
- return client
361
-
362
- # 创建新客户端
363
- initial_queue_name = kwargs.pop('queue_name', '')
364
- is_sender = not cls._has_listeners or (
365
- not kwargs.get('create_if_not_exists', True))
366
-
367
- # 发送器特殊处理
368
- if is_sender:
369
- kwargs['create_if_not_exists'] = False
370
- client = await cls._create_client(
371
- initial_queue_name,
372
- app_name=cls._config.get("APP_NAME", ""),
373
- **kwargs
374
- )
375
- cls._clients[client_name] = client
376
- return client
377
-
378
- # 监听器逻辑
379
- kwargs['create_if_not_exists'] = True
380
-
381
- # 检查队列是否已初始化
382
- if initial_queue_name in cls._initialized_queues:
383
- logger.info(f"队列 '{initial_queue_name}' 已初始化,直接创建客户端")
384
- client = await cls._create_client(initial_queue_name, **kwargs)
385
- cls._clients[client_name] = client
386
- return client
387
-
388
- # 创建并连接客户端
389
- client = await cls._create_client(
390
- initial_queue_name,
391
- app_name=cls._config.get("APP_NAME", ""),
392
- **kwargs
393
- )
394
-
395
- # 验证队列是否创建成功
396
- if not client._queue:
397
- logger.error(f"队列 '{initial_queue_name}' 创建失败,尝试重新创建")
398
- client.create_if_not_exists = True
399
- await client.connect()
400
- if not client._queue:
401
- raise Exception(f"无法创建队列 '{initial_queue_name}'")
402
-
403
- # 记录已初始化的队列
404
- final_queue_name = client.queue_name
405
- if final_queue_name:
406
- cls._initialized_queues.add(final_queue_name)
407
-
408
- cls._clients[client_name] = client
409
- return client
410
-
411
- @classmethod
412
- async def setup_senders(cls, senders: List[RabbitMQSendConfig], has_listeners: bool = False, **kwargs) -> None:
413
- """设置消息发送器(适配新客户端)"""
414
- if cls._is_shutdown:
415
- logger.warning("服务已关闭,无法设置发送器")
416
- return
417
-
418
- cls._has_senders = True
419
- cls._has_listeners = has_listeners
420
- logger.info(f"开始设置 {len(senders)} 个消息发送器")
421
-
422
- for idx, sender_config in enumerate(senders):
423
- try:
424
- if not sender_config.queue_name:
425
- raise ValueError(f"发送器配置第{idx+1}项缺少queue_name")
426
-
427
- prefetch_count = sender_config.prefetch_count
428
- queue_name = sender_config.queue_name
429
- app_name = cls._config.get(
430
- "APP_NAME", "") if cls._config else ""
431
-
432
- # 处理发送器队列名称,移除可能的app-name后缀
433
- normalized_name = queue_name
434
- if app_name and normalized_name.endswith(f".{app_name}"):
435
- normalized_name = normalized_name[:-len(f".{app_name}")]
436
- logger.info(f"发送器队列名称移除app-name后缀: {normalized_name}")
437
-
438
- # 检查是否已初始化
439
- if normalized_name in cls._sender_client_names:
440
- logger.info(f"发送客户端 '{normalized_name}' 已存在,跳过")
441
- continue
442
-
443
- # 获取或创建客户端
444
- if normalized_name in cls._clients:
445
- client = cls._clients[normalized_name]
446
- if not await client.is_connected:
447
- await client.connect()
448
- else:
449
- client = await cls.get_client(
450
- client_name=normalized_name,
451
- exchange_type=sender_config.exchange_type,
452
- durable=sender_config.durable,
453
- auto_delete=sender_config.auto_delete,
454
- auto_parse_json=sender_config.auto_parse_json,
455
- queue_name=queue_name,
456
- create_if_not_exists=False,
457
- prefetch_count=prefetch_count,
458
- **kwargs
459
- )
460
-
461
- # 记录客户端
462
- if normalized_name not in cls._clients:
463
- cls._clients[normalized_name] = client
464
- logger.info(f"发送客户端 '{normalized_name}' 已添加")
465
-
466
- if normalized_name not in cls._sender_client_names:
467
- cls._sender_client_names.append(normalized_name)
468
- logger.info(f"发送客户端 '{normalized_name}' 初始化成功")
469
-
470
- except Exception as e:
471
- logger.error(
472
- f"初始化发送客户端第{idx+1}项失败: {str(e)}", exc_info=True)
473
-
474
- logger.info(f"消息发送器设置完成,共 {len(cls._sender_client_names)} 个发送器")
475
-
476
- @classmethod
477
- async def setup_listeners(cls, listeners: List[RabbitMQListenerConfig], has_senders: bool = False, **kwargs) -> None:
478
- """设置消息监听器(适配新客户端)"""
479
- if cls._is_shutdown:
480
- logger.warning("服务已关闭,无法设置监听器")
481
- return
482
-
483
- cls._has_listeners = True
484
- cls._has_senders = has_senders
485
- logger.info(f"开始设置 {len(listeners)} 个消息监听器")
486
-
487
- for idx, listener_config in enumerate(listeners):
488
- try:
489
- # 转换配置并强制设置create_if_not_exists为True
490
- listener_dict = listener_config.model_dump()
491
- listener_dict['create_if_not_exists'] = True
492
- listener_dict['prefetch_count'] = listener_config.prefetch_count
493
- queue_name = listener_dict['queue_name']
494
-
495
- logger.info(
496
- f"设置监听器 {idx+1}/{len(listeners)}: {queue_name} (prefetch_count: {listener_config.prefetch_count})")
497
-
498
- # 添加监听器
499
- await cls.add_listener(**listener_dict)
500
- except Exception as e:
501
- logger.error(
502
- f"设置监听器 {idx+1} 失败: {str(e)}", exc_info=True)
503
- logger.warning("继续处理其他监听器")
504
-
505
- # 启动所有消费者
506
- await cls.start_all_consumers()
507
-
508
- # 验证消费者启动结果
509
- await cls._verify_consumers_started()
510
-
511
- logger.info(f"消息监听器设置完成")
512
-
513
- @classmethod
514
- async def _verify_consumers_started(cls, timeout: int = 30) -> None:
515
- """验证消费者是否成功启动"""
516
- start_time = asyncio.get_event_loop().time()
517
- required_clients = list(cls._message_handlers.keys())
518
- running_clients = []
519
-
520
- while len(running_clients) < len(required_clients) and \
521
- (asyncio.get_event_loop().time() - start_time) < timeout and \
522
- not cls._is_shutdown:
523
-
524
- running_clients = [
525
- name for name, task in cls._consumer_tasks.items()
526
- if not task.done() and name in cls._consumer_tags
527
- ]
528
-
529
- logger.info(
530
- f"消费者启动验证: {len(running_clients)}/{len(required_clients)} 已启动")
531
- await asyncio.sleep(1)
532
-
533
- failed_clients = [
534
- name for name in required_clients if name not in running_clients and not cls._is_shutdown]
535
- if failed_clients:
536
- logger.error(f"以下消费者启动失败: {', '.join(failed_clients)}")
537
- for client_name in failed_clients:
538
- logger.info(f"尝试重新启动消费者: {client_name}")
539
- asyncio.create_task(cls.start_consumer(client_name))
540
-
541
- @classmethod
542
- async def add_listener(
543
- cls,
544
- queue_name: str,
545
- handler: Callable[[MQMsgModel, AbstractIncomingMessage], Coroutine[Any, Any, None]], **kwargs
546
- ) -> None:
547
- """添加消息监听器(线程安全)"""
548
- if cls._is_shutdown:
549
- logger.warning("服务已关闭,无法添加监听器")
550
- return
551
-
552
- if not cls._config:
553
- raise ValueError("RabbitMQService尚未初始化,请先调用init方法")
554
-
555
- if queue_name in cls._message_handlers:
556
- logger.info(f"监听器 '{queue_name}' 已存在,跳过重复添加")
557
- return
558
-
559
- # 创建并初始化客户端
560
- await cls.get_client(
561
- client_name=queue_name,
562
- queue_name=queue_name,
563
- **kwargs
564
- )
565
-
566
- # 注册消息处理器
567
- cls._message_handlers[queue_name] = handler
568
- logger.info(f"监听器 '{queue_name}' 已添加")
569
-
570
- @classmethod
571
- async def start_all_consumers(cls) -> None:
572
- """启动所有已注册的消费者(线程安全)"""
573
- if cls._is_shutdown:
574
- logger.warning("服务已关闭,无法启动消费者")
575
- return
576
-
577
- for client_name in cls._message_handlers:
578
- await cls.start_consumer(client_name)
579
-
580
- @classmethod
581
- async def start_consumer(cls, client_name: str) -> None:
582
- """启动指定客户端的消费者"""
583
- if cls._is_shutdown:
584
- logger.warning("服务已关闭,无法启动消费者")
585
- return
586
-
587
- # 检查任务状态,避免重复创建
588
- if client_name in cls._consumer_tasks:
589
- existing_task = cls._consumer_tasks[client_name]
590
- if not existing_task.done():
591
- # 检查任务是否处于异常状态,仅在异常时重启
592
- if existing_task.exception() is not None:
593
- logger.info(f"消费者 '{client_name}' 任务异常,重启")
594
- existing_task.cancel()
595
- else:
596
- logger.info(f"消费者 '{client_name}' 已在运行中,无需重复启动")
597
- return
598
- else:
599
- logger.info(f"消费者 '{client_name}' 任务已完成,重新启动")
600
-
601
- if client_name not in cls._clients:
602
- raise ValueError(f"RabbitMQ客户端 '{client_name}' 未初始化")
603
-
604
- client = cls._clients[client_name]
605
- handler = cls._message_handlers.get(client_name)
606
-
607
- if not handler:
608
- logger.warning(f"未找到客户端 '{client_name}' 的处理器,使用默认处理器")
609
- handler = cls.default_message_handler
610
-
611
- # 设置消息处理器
612
- await client.set_message_handler(handler)
613
-
614
- # 确保客户端已连接
615
- start_time = asyncio.get_event_loop().time()
616
- while not await client.is_connected and not cls._is_shutdown:
617
- if asyncio.get_event_loop().time() - start_time > cls.CONSUMER_START_TIMEOUT:
618
- raise TimeoutError(f"等待客户端 '{client_name}' 连接超时")
619
-
620
- logger.info(f"等待客户端 '{client_name}' 连接就绪...")
621
- await asyncio.sleep(1)
622
- if cls._is_shutdown:
623
- return
624
-
625
- # 监听器启动消费前额外延迟1秒
626
- if cls._has_listeners and not client_name.startswith("sender-"):
627
- logger.info(f"消费者 '{client_name}' 准备启动,延迟1秒等待消费状态就绪")
628
- await asyncio.sleep(1)
629
-
630
- # 创建停止事件
631
- stop_event = asyncio.Event()
632
- cls._consumer_events[client_name] = stop_event
633
-
634
- # 定义消费任务
635
- async def consume_task():
636
- try:
637
- # 启动消费,带重试机制
638
- max_attempts = 5
639
- attempt = 0
640
- consumer_tag = None
641
-
642
- while attempt < max_attempts and not stop_event.is_set() and not cls._is_shutdown:
643
- try:
644
- # 启动消费前再次校验连接和队列状态
645
- if not await client.is_connected:
646
- logger.info(f"消费者 '{client_name}' 连接断开,尝试重连")
647
- await client.connect()
648
-
649
- # 确保队列和处理器已就绪
650
- if not client._queue:
651
- raise Exception("队列未初始化完成")
652
- if not client._message_handler:
653
- raise Exception("消息处理器未设置")
654
-
655
- consumer_tag = await client.start_consuming()
656
- if consumer_tag:
657
- break
658
- except Exception as e:
659
- attempt += 1
660
- logger.warning(
661
- f"启动消费者尝试 {attempt}/{max_attempts} 失败: {str(e)}")
662
- if attempt < max_attempts:
663
- await asyncio.sleep(2)
664
-
665
- if cls._is_shutdown:
666
- return
667
-
668
- if not consumer_tag:
669
- raise Exception(f"经过 {max_attempts} 次尝试仍无法启动消费者")
670
-
671
- # 记录消费者标签
672
- cls._consumer_tags[client_name] = consumer_tag
673
- logger.info(
674
- f"消费者 '{client_name}' 开始消费,tag: {consumer_tag}")
675
-
676
- # 等待停止事件
677
- await stop_event.wait()
678
- logger.info(f"收到停止信号,消费者 '{client_name}' 准备退出")
679
-
680
- except asyncio.CancelledError:
681
- logger.info(f"消费者 '{client_name}' 被取消")
682
- except Exception as e:
683
- logger.error(
684
- f"消费者 '{client_name}' 错误: {str(e)}", exc_info=True)
685
- # 非主动停止时尝试重启
686
- if not stop_event.is_set() and not cls._is_shutdown:
687
- logger.info(f"尝试重启消费者 '{client_name}'")
688
- await asyncio.sleep(cls.RECONNECT_INTERVAL)
689
- asyncio.create_task(cls.start_consumer(client_name))
690
- finally:
691
- # 清理资源
692
- try:
693
- await client.stop_consuming()
694
- except Exception as e:
695
- logger.error(f"停止消费者 '{client_name}' 时出错: {str(e)}")
696
-
697
- # 移除状态记录
698
- if client_name in cls._consumer_tags:
699
- del cls._consumer_tags[client_name]
700
- if client_name in cls._consumer_events:
701
- del cls._consumer_events[client_name]
702
-
703
- logger.info(f"消费者 '{client_name}' 已停止")
704
-
705
- # 创建并跟踪消费任务
706
- task = asyncio.create_task(
707
- consume_task(), name=f"consumer-{client_name}")
708
- cls._consumer_tasks[client_name] = task
709
-
710
- # 添加任务完成回调
711
- def task_done_callback(t: asyncio.Task) -> None:
712
- try:
713
- if t.done():
714
- t.result()
715
- except Exception as e:
716
- logger.error(f"消费者任务 '{client_name}' 异常结束: {str(e)}")
717
- if client_name in cls._message_handlers and not cls._is_shutdown:
718
- asyncio.create_task(cls.start_consumer(client_name))
719
-
720
- task.add_done_callback(task_done_callback)
721
- logger.info(f"消费者任务 '{client_name}' 已创建")
722
-
723
- @classmethod
724
- async def default_message_handler(cls, parsed_data: MQMsgModel, original_message: AbstractIncomingMessage) -> None:
725
- """默认消息处理器"""
726
- logger.info(f"\n===== 收到消息 [{original_message.routing_key}] =====")
727
- logger.info(f"关联ID: {parsed_data.correlationDataId}")
728
- logger.info(f"主题代码: {parsed_data.topicCode}")
729
- logger.info(f"消息内容: {parsed_data.msg}")
730
- logger.info("===================\n")
731
-
732
- @classmethod
733
- async def get_sender(cls, queue_name: str) -> Optional[RabbitMQClient]:
734
- """获取发送客户端"""
735
- if cls._is_shutdown:
736
- logger.warning("服务已关闭,无法获取发送器")
737
- return None
738
-
739
- if not queue_name:
740
- logger.warning("发送器名称不能为空")
741
- return None
742
-
743
- # 检查是否在已注册的发送器中
744
- if queue_name in cls._sender_client_names and queue_name in cls._clients:
745
- client = cls._clients[queue_name]
746
- if await client.is_connected:
747
- return client
748
- else:
749
- logger.info(f"发送器 '{queue_name}' 连接已断开,尝试重连")
750
- try:
751
- await client.connect()
752
- if await client.is_connected:
753
- return client
754
- except Exception as e:
755
- logger.error(f"发送器 '{queue_name}' 重连失败: {str(e)}")
756
- return None
757
-
758
- # 检查是否带有app-name后缀
759
- app_name = cls._config.get("APP_NAME", "") if cls._config else ""
760
- if app_name:
761
- suffixed_name = f"{queue_name}.{app_name}"
762
- if suffixed_name in cls._sender_client_names and suffixed_name in cls._clients:
763
- client = cls._clients[suffixed_name]
764
- if await client.is_connected:
765
- return client
766
- else:
767
- logger.info(f"发送器 '{suffixed_name}' 连接已断开,尝试重连")
768
- try:
769
- await client.connect()
770
- if await client.is_connected:
771
- return client
772
- except Exception as e:
773
- logger.error(f"发送器 '{suffixed_name}' 重连失败: {str(e)}")
774
-
775
- logger.info(f"未找到可用的发送器 '{queue_name}'")
776
- return None
777
-
778
- @classmethod
779
- async def send_message(
780
- cls,
781
- data: Union[BaseModel, str, Dict[str, Any], None],
782
- queue_name: str, **kwargs
783
- ) -> None:
784
- """发送消息到指定队列"""
785
- if cls._is_shutdown:
786
- raise RuntimeError("RabbitMQService已关闭,无法发送消息")
787
-
788
- # 获取发送客户端
789
- sender = await cls.get_sender(queue_name)
790
- if not sender:
791
- error_msg = f"未找到可用的RabbitMQ发送器 (queue_name: {queue_name})"
792
- logger.error(error_msg)
793
- raise ValueError(error_msg)
794
-
795
- # 确保连接有效
796
- if not await sender.is_connected:
797
- logger.info(f"发送器 '{queue_name}' 连接已关闭,尝试重新连接")
798
- max_retry = 3
799
- retry_count = 0
800
- last_exception = None
801
-
802
- while retry_count < max_retry and not cls._is_shutdown:
803
- try:
804
- await sender.connect()
805
- if await sender.is_connected:
806
- logger.info(
807
- f"发送器 '{queue_name}' 第 {retry_count + 1} 次重连成功")
808
- break
809
- except Exception as e:
810
- last_exception = e
811
- retry_count += 1
812
- logger.warning(
813
- f"发送器 '{queue_name}' 第 {retry_count} 次重连失败: {str(e)}")
814
- await asyncio.sleep(cls.RECONNECT_INTERVAL)
815
-
816
- if retry_count >= max_retry and not await sender.is_connected:
817
- error_msg = f"发送器 '{queue_name}' 经过 {max_retry} 次重连仍失败"
818
- logger.error(f"{error_msg}: {str(last_exception)}")
819
- raise Exception(error_msg) from last_exception
820
-
821
- try:
822
- # 处理消息数据
823
- msg_content = ""
824
- if isinstance(data, str):
825
- msg_content = data
826
- elif isinstance(data, BaseModel):
827
- msg_content = data.model_dump_json()
828
- elif isinstance(data, dict):
829
- msg_content = json.dumps(data, ensure_ascii=False)
830
-
831
- # 创建标准消息模型
832
- mq_message = MQMsgModel(
833
- topicCode=queue_name.split('.')[0] if queue_name else "",
834
- msg=msg_content,
835
- correlationDataId=kwargs.get(
836
- 'correlationDataId', logger.get_trace_id()),
837
- groupId=kwargs.get('groupId', ''),
838
- dataKey=kwargs.get('dataKey', ""),
839
- manualFlag=kwargs.get('manualFlag', False),
840
- traceId=logger.get_trace_id()
841
- )
842
-
843
- # 构建消息头
844
- mq_header = {
845
- "context": SsoUser(
846
- tenant_id="T000002",
847
- customer_id="SYSTEM",
848
- user_id="SYSTEM",
849
- user_name="SYSTEM",
850
- request_path="",
851
- req_type="SYSTEM",
852
- trace_id=logger.get_trace_id(),
853
- ).model_dump_json()
854
- }
855
-
856
- # 发送消息
857
- await sender.publish(
858
- message_body=mq_message.model_dump_json(),
859
- headers=mq_header,
860
- content_type="application/json"
861
- )
862
- logger.info(f"消息发送成功 (队列: {queue_name})")
863
- except Exception as e:
864
- logger.error(f"消息发送失败: {str(e)}", exc_info=True)
865
- raise
866
-
867
33
  @classmethod
868
34
  async def shutdown(cls, timeout: float = 15.0) -> None:
869
- """优雅关闭所有资源(线程安全)"""
35
+ """优雅关闭所有资源(保持原有接口)"""
870
36
  async with cls._shutdown_lock:
871
37
  if cls._is_shutdown:
872
38
  logger.info("RabbitMQService已关闭,无需重复操作")
@@ -876,52 +42,18 @@ class RabbitMQService:
876
42
  logger.info("开始关闭RabbitMQ服务...")
877
43
 
878
44
  # 1. 停止连接监控任务
879
- if cls._connection_monitor_task and not cls._connection_monitor_task.done():
880
- cls._connection_monitor_task.cancel()
881
- try:
882
- await asyncio.wait_for(cls._connection_monitor_task, timeout=timeout)
883
- except asyncio.TimeoutError:
884
- logger.warning("连接监控任务关闭超时")
885
- except Exception as e:
886
- logger.error(f"关闭连接监控任务失败: {str(e)}")
45
+ await cls.stop_connection_monitor(timeout)
887
46
 
888
47
  # 2. 停止所有消费者任务
889
- for client_name, task in cls._consumer_tasks.items():
890
- if not task.done():
891
- # 触发停止事件
892
- if client_name in cls._consumer_events:
893
- cls._consumer_events[client_name].set()
894
- # 取消任务
895
- task.cancel()
896
- try:
897
- await asyncio.wait_for(task, timeout=timeout)
898
- except Exception as e:
899
- logger.error(f"关闭消费者 '{client_name}' 失败: {str(e)}")
48
+ await cls.shutdown_consumers(timeout)
900
49
 
901
50
  # 3. 关闭所有客户端
902
- for client in cls._clients.values():
903
- try:
904
- await client.close()
905
- except Exception as e:
906
- logger.error(f"关闭客户端失败: {str(e)}")
51
+ await cls.shutdown_clients(timeout)
907
52
 
908
53
  # 4. 关闭连接池
909
- if cls._connection_pool and cls._connection_pool._initialized:
910
- try:
911
- await cls._connection_pool.close()
912
- logger.info("RabbitMQ连接池已关闭")
913
- except Exception as e:
914
- logger.error(f"关闭连接池失败: {str(e)}")
54
+ await cls.shutdown_core_resources(timeout)
915
55
 
916
- # 5. 清理状态
917
- cls._clients.clear()
918
- cls._message_handlers.clear()
919
- cls._consumer_tasks.clear()
920
- cls._consumer_events.clear()
921
- cls._consumer_tags.clear()
922
- cls._initialized_queues.clear()
923
- cls._sender_client_names.clear()
924
- cls._init_locks.clear()
925
- cls._config = None
56
+ # 5. 清理剩余状态
57
+ cls.clear_senders()
926
58
 
927
59
  logger.info("RabbitMQService已完全关闭")