crawlo 1.1.3__py3-none-any.whl → 1.1.4__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.

Potentially problematic release.


This version of crawlo might be problematic. Click here for more details.

Files changed (118) hide show
  1. crawlo/__init__.py +34 -34
  2. crawlo/__version__.py +1 -1
  3. crawlo/cli.py +40 -40
  4. crawlo/commands/__init__.py +13 -13
  5. crawlo/commands/check.py +594 -594
  6. crawlo/commands/genspider.py +151 -151
  7. crawlo/commands/list.py +155 -155
  8. crawlo/commands/run.py +285 -285
  9. crawlo/commands/startproject.py +196 -196
  10. crawlo/commands/stats.py +188 -188
  11. crawlo/commands/utils.py +186 -186
  12. crawlo/config.py +279 -279
  13. crawlo/core/__init__.py +2 -2
  14. crawlo/core/engine.py +171 -171
  15. crawlo/core/enhanced_engine.py +189 -189
  16. crawlo/core/processor.py +40 -40
  17. crawlo/core/scheduler.py +165 -165
  18. crawlo/crawler.py +1027 -1027
  19. crawlo/downloader/__init__.py +242 -242
  20. crawlo/downloader/aiohttp_downloader.py +212 -212
  21. crawlo/downloader/cffi_downloader.py +251 -251
  22. crawlo/downloader/httpx_downloader.py +259 -259
  23. crawlo/event.py +11 -11
  24. crawlo/exceptions.py +81 -81
  25. crawlo/extension/__init__.py +38 -31
  26. crawlo/extension/health_check.py +142 -0
  27. crawlo/extension/log_interval.py +58 -49
  28. crawlo/extension/log_stats.py +82 -44
  29. crawlo/extension/logging_extension.py +44 -35
  30. crawlo/extension/memory_monitor.py +89 -0
  31. crawlo/extension/performance_profiler.py +118 -0
  32. crawlo/extension/request_recorder.py +108 -0
  33. crawlo/filters/__init__.py +154 -154
  34. crawlo/filters/aioredis_filter.py +241 -241
  35. crawlo/filters/memory_filter.py +269 -269
  36. crawlo/items/__init__.py +23 -23
  37. crawlo/items/base.py +21 -21
  38. crawlo/items/fields.py +53 -53
  39. crawlo/items/items.py +104 -104
  40. crawlo/middleware/__init__.py +21 -21
  41. crawlo/middleware/default_header.py +32 -32
  42. crawlo/middleware/download_delay.py +28 -28
  43. crawlo/middleware/middleware_manager.py +135 -135
  44. crawlo/middleware/proxy.py +248 -248
  45. crawlo/middleware/request_ignore.py +30 -30
  46. crawlo/middleware/response_code.py +18 -18
  47. crawlo/middleware/response_filter.py +26 -26
  48. crawlo/middleware/retry.py +124 -124
  49. crawlo/mode_manager.py +200 -200
  50. crawlo/network/__init__.py +21 -21
  51. crawlo/network/request.py +311 -311
  52. crawlo/network/response.py +271 -271
  53. crawlo/pipelines/__init__.py +21 -21
  54. crawlo/pipelines/bloom_dedup_pipeline.py +156 -156
  55. crawlo/pipelines/console_pipeline.py +39 -39
  56. crawlo/pipelines/csv_pipeline.py +316 -316
  57. crawlo/pipelines/database_dedup_pipeline.py +224 -224
  58. crawlo/pipelines/json_pipeline.py +218 -218
  59. crawlo/pipelines/memory_dedup_pipeline.py +115 -115
  60. crawlo/pipelines/mongo_pipeline.py +132 -117
  61. crawlo/pipelines/mysql_pipeline.py +317 -195
  62. crawlo/pipelines/pipeline_manager.py +56 -56
  63. crawlo/pipelines/redis_dedup_pipeline.py +162 -162
  64. crawlo/project.py +153 -153
  65. crawlo/queue/pqueue.py +37 -37
  66. crawlo/queue/queue_manager.py +307 -307
  67. crawlo/queue/redis_priority_queue.py +208 -208
  68. crawlo/settings/__init__.py +7 -7
  69. crawlo/settings/default_settings.py +278 -244
  70. crawlo/settings/setting_manager.py +99 -99
  71. crawlo/spider/__init__.py +639 -639
  72. crawlo/stats_collector.py +59 -59
  73. crawlo/subscriber.py +131 -106
  74. crawlo/task_manager.py +30 -30
  75. crawlo/templates/crawlo.cfg.tmpl +10 -10
  76. crawlo/templates/project/__init__.py.tmpl +3 -3
  77. crawlo/templates/project/items.py.tmpl +17 -17
  78. crawlo/templates/project/middlewares.py.tmpl +111 -87
  79. crawlo/templates/project/pipelines.py.tmpl +97 -341
  80. crawlo/templates/project/run.py.tmpl +251 -251
  81. crawlo/templates/project/settings.py.tmpl +279 -250
  82. crawlo/templates/project/spiders/__init__.py.tmpl +5 -5
  83. crawlo/templates/spider/spider.py.tmpl +142 -178
  84. crawlo/utils/__init__.py +7 -7
  85. crawlo/utils/controlled_spider_mixin.py +439 -439
  86. crawlo/utils/date_tools.py +233 -233
  87. crawlo/utils/db_helper.py +343 -343
  88. crawlo/utils/func_tools.py +82 -82
  89. crawlo/utils/large_scale_config.py +286 -286
  90. crawlo/utils/large_scale_helper.py +343 -343
  91. crawlo/utils/log.py +128 -128
  92. crawlo/utils/queue_helper.py +175 -175
  93. crawlo/utils/request.py +267 -267
  94. crawlo/utils/request_serializer.py +219 -219
  95. crawlo/utils/spider_loader.py +62 -62
  96. crawlo/utils/system.py +11 -11
  97. crawlo/utils/tools.py +4 -4
  98. crawlo/utils/url.py +39 -39
  99. crawlo-1.1.4.dist-info/METADATA +403 -0
  100. crawlo-1.1.4.dist-info/RECORD +117 -0
  101. examples/__init__.py +7 -7
  102. examples/controlled_spider_example.py +205 -205
  103. tests/__init__.py +7 -7
  104. tests/test_final_validation.py +153 -153
  105. tests/test_proxy_health_check.py +32 -32
  106. tests/test_proxy_middleware_integration.py +136 -136
  107. tests/test_proxy_providers.py +56 -56
  108. tests/test_proxy_stats.py +19 -19
  109. tests/test_proxy_strategies.py +59 -59
  110. tests/test_redis_config.py +28 -28
  111. tests/test_redis_queue.py +224 -224
  112. tests/test_request_serialization.py +70 -70
  113. tests/test_scheduler.py +241 -241
  114. crawlo-1.1.3.dist-info/METADATA +0 -635
  115. crawlo-1.1.3.dist-info/RECORD +0 -113
  116. {crawlo-1.1.3.dist-info → crawlo-1.1.4.dist-info}/WHEEL +0 -0
  117. {crawlo-1.1.3.dist-info → crawlo-1.1.4.dist-info}/entry_points.txt +0 -0
  118. {crawlo-1.1.3.dist-info → crawlo-1.1.4.dist-info}/top_level.txt +0 -0
@@ -1,242 +1,242 @@
1
- #!/usr/bin/python
2
- # -*- coding:UTF-8 -*-
3
- """
4
- Redis 过滤器实现
5
- =================
6
- 提供基于 Redis 的分布式请求去重功能。
7
-
8
- 特点:
9
- - 分布式支持: 多节点共享去重数据
10
- - TTL 支持: 自动过期清理
11
- - 高性能: 使用 Redis pipeline 优化
12
- - 容错设计: 网络异常自动重试
13
- """
14
- import redis.asyncio as aioredis
15
- from typing import Optional
16
- from crawlo.filters import BaseFilter
17
- from crawlo.utils.log import get_logger
18
- from crawlo.utils.request import request_fingerprint
19
-
20
-
21
- class AioRedisFilter(BaseFilter):
22
- """
23
- 基于Redis集合实现的异步请求去重过滤器
24
-
25
- 支持特性:
26
- - 分布式爬虫多节点共享去重数据
27
- - TTL 自动过期清理机制
28
- - Pipeline 批量操作优化性能
29
- - 容错设计和连接池管理
30
-
31
- 适用场景:
32
- - 分布式爬虫系统
33
- - 大规模数据处理
34
- - 需要持久化去重的场景
35
- """
36
-
37
- def __init__(
38
- self,
39
- redis_key: str,
40
- client: aioredis.Redis,
41
- stats: dict,
42
- debug: bool = False,
43
- log_level: str = 'INFO',
44
- cleanup_fp: bool = False,
45
- ttl: Optional[int] = None
46
- ):
47
- """
48
- 初始化Redis过滤器
49
-
50
- :param redis_key: Redis中存储指纹的键名
51
- :param client: Redis客户端实例
52
- :param stats: 统计信息存储
53
- :param debug: 是否启用调试模式
54
- :param log_level: 日志级别
55
- :param cleanup_fp: 关闭时是否清理指纹
56
- :param ttl: 指纹过期时间(秒)
57
- """
58
- self.logger = get_logger(self.__class__.__name__, log_level)
59
- super().__init__(self.logger, stats, debug)
60
-
61
- self.redis_key = redis_key
62
- self.redis = client
63
- self.cleanup_fp = cleanup_fp
64
- self.ttl = ttl
65
-
66
- # 性能计数器
67
- self._redis_operations = 0
68
- self._pipeline_operations = 0
69
-
70
- @classmethod
71
- def create_instance(cls, crawler) -> 'BaseFilter':
72
- """从爬虫配置创建过滤器实例"""
73
- redis_url = crawler.settings.get('REDIS_URL', 'redis://localhost:6379')
74
- decode_responses = crawler.settings.get_bool('DECODE_RESPONSES', False)
75
- ttl_setting = crawler.settings.get_int('REDIS_TTL')
76
-
77
- # 处理TTL设置
78
- ttl = None
79
- if ttl_setting is not None:
80
- ttl = max(0, int(ttl_setting)) if ttl_setting > 0 else None
81
-
82
- try:
83
- redis_client = aioredis.from_url(
84
- redis_url,
85
- decode_responses=decode_responses,
86
- max_connections=20,
87
- encoding='utf-8'
88
- )
89
- except Exception as e:
90
- raise RuntimeError(f"Redis连接失败: {redis_url} - {str(e)}")
91
-
92
- return cls(
93
- redis_key=f"{crawler.settings.get('PROJECT_NAME', 'default')}:{crawler.settings.get('REDIS_KEY', 'request_fingerprints')}",
94
- client=redis_client,
95
- stats=crawler.stats,
96
- cleanup_fp=crawler.settings.get_bool('CLEANUP_FP', False),
97
- ttl=ttl,
98
- debug=crawler.settings.get_bool('FILTER_DEBUG', False),
99
- log_level=crawler.settings.get('LOG_LEVEL', 'INFO')
100
- )
101
-
102
- async def requested(self, request) -> bool:
103
- """
104
- 检查请求是否已存在(优化版本)
105
-
106
- :param request: 请求对象
107
- :return: True 表示重复,False 表示新请求
108
- """
109
- try:
110
- fp = str(request_fingerprint(request))
111
- self._redis_operations += 1
112
-
113
- # 使用 pipeline 优化性能
114
- pipe = self.redis.pipeline()
115
- pipe.sismember(self.redis_key, fp)
116
-
117
- results = await pipe.execute()
118
- exists = results[0]
119
-
120
- self._pipeline_operations += 1
121
-
122
- if exists:
123
- if self.debug:
124
- self.logger.debug(f"发现重复请求: {fp[:20]}...")
125
- return True
126
-
127
- # 如果不存在,添加指纹并设置TTL
128
- await self.add_fingerprint(fp)
129
- return False
130
-
131
- except Exception as e:
132
- self.logger.error(f"请求检查失败: {getattr(request, 'url', '未知URL')} - {e}")
133
- # 在网络异常时返回False,避免丢失请求
134
- return False
135
-
136
- async def add_fingerprint(self, fp: str) -> bool:
137
- """
138
- 添加新指纹到Redis集合(优化版本)
139
-
140
- :param fp: 请求指纹字符串
141
- :return: 是否成功添加(True 表示新添加,False 表示已存在)
142
- """
143
- try:
144
- fp = str(fp)
145
-
146
- # 使用 pipeline 优化性能
147
- pipe = self.redis.pipeline()
148
- pipe.sadd(self.redis_key, fp)
149
-
150
- if self.ttl and self.ttl > 0:
151
- pipe.expire(self.redis_key, self.ttl)
152
-
153
- results = await pipe.execute()
154
- added = results[0] == 1 # sadd 返回 1 表示新添加
155
-
156
- self._pipeline_operations += 1
157
-
158
- if self.debug and added:
159
- self.logger.debug(f"添加新指纹: {fp[:20]}...")
160
-
161
- return added
162
-
163
- except Exception as e:
164
- self.logger.error(f"添加指纹失败: {fp[:20]}... - {e}")
165
- return False
166
-
167
- def __contains__(self, item: str) -> bool:
168
- """
169
- 同步版本的包含检查(不推荐在异步环境中使用)
170
-
171
- :param item: 要检查的指纹
172
- :return: 是否已存在
173
- """
174
- # 这是一个同步方法,不能直接调用异步Redis操作
175
- # 建议使用 requested() 方法替代
176
- raise NotImplementedError("请使用 requested() 方法进行异步检查")
177
-
178
- async def get_stats(self) -> dict:
179
- """获取过滤器详细统计信息"""
180
- try:
181
- count = await self.redis.scard(self.redis_key)
182
-
183
- # 获取TTL信息
184
- ttl_info = "TTL未设置"
185
- if self.ttl:
186
- remaining_ttl = await self.redis.ttl(self.redis_key)
187
- if remaining_ttl > 0:
188
- ttl_info = f"剩余 {remaining_ttl} 秒"
189
- else:
190
- ttl_info = f"配置 {self.ttl} 秒"
191
-
192
- stats = {
193
- 'filter_type': 'AioRedisFilter',
194
- '指纹总数': count,
195
- 'Redis键名': self.redis_key,
196
- 'TTL配置': ttl_info,
197
- 'Redis操作数': self._redis_operations,
198
- 'Pipeline操作数': self._pipeline_operations,
199
- '性能优化率': f"{self._pipeline_operations / max(1, self._redis_operations) * 100:.1f}%"
200
- }
201
-
202
- # 合并基类统计
203
- base_stats = super().get_stats()
204
- stats.update(base_stats)
205
-
206
- return stats
207
-
208
- except Exception as e:
209
- self.logger.error(f"获取统计信息失败: {e}")
210
- return super().get_stats()
211
-
212
- async def clear_all(self) -> int:
213
- """清空所有指纹数据"""
214
- try:
215
- deleted = await self.redis.delete(self.redis_key)
216
- self.logger.info(f"已清除指纹数: {deleted}")
217
- return deleted
218
- except Exception as e:
219
- self.logger.error("清空指纹失败")
220
- raise
221
-
222
- async def closed(self, reason: Optional[str] = None) -> None:
223
- """爬虫关闭时的清理操作"""
224
- try:
225
- if self.cleanup_fp:
226
- deleted = await self.redis.delete(self.redis_key)
227
- self.logger.info(f"爬虫关闭清理: 已删除{deleted}个指纹")
228
- else:
229
- count = await self.redis.scard(self.redis_key)
230
- ttl_info = f"{self.ttl}秒" if self.ttl else "持久化"
231
- self.logger.info(f"保留指纹数: {count} (TTL: {ttl_info})")
232
- finally:
233
- await self._close_redis()
234
-
235
- async def _close_redis(self) -> None:
236
- """安全关闭Redis连接"""
237
- try:
238
- if hasattr(self.redis, 'close'):
239
- await self.redis.close()
240
- self.logger.debug("Redis连接已关闭")
241
- except Exception as e:
1
+ #!/usr/bin/python
2
+ # -*- coding:UTF-8 -*-
3
+ """
4
+ Redis 过滤器实现
5
+ =================
6
+ 提供基于 Redis 的分布式请求去重功能。
7
+
8
+ 特点:
9
+ - 分布式支持: 多节点共享去重数据
10
+ - TTL 支持: 自动过期清理
11
+ - 高性能: 使用 Redis pipeline 优化
12
+ - 容错设计: 网络异常自动重试
13
+ """
14
+ import redis.asyncio as aioredis
15
+ from typing import Optional
16
+ from crawlo.filters import BaseFilter
17
+ from crawlo.utils.log import get_logger
18
+ from crawlo.utils.request import request_fingerprint
19
+
20
+
21
+ class AioRedisFilter(BaseFilter):
22
+ """
23
+ 基于Redis集合实现的异步请求去重过滤器
24
+
25
+ 支持特性:
26
+ - 分布式爬虫多节点共享去重数据
27
+ - TTL 自动过期清理机制
28
+ - Pipeline 批量操作优化性能
29
+ - 容错设计和连接池管理
30
+
31
+ 适用场景:
32
+ - 分布式爬虫系统
33
+ - 大规模数据处理
34
+ - 需要持久化去重的场景
35
+ """
36
+
37
+ def __init__(
38
+ self,
39
+ redis_key: str,
40
+ client: aioredis.Redis,
41
+ stats: dict,
42
+ debug: bool = False,
43
+ log_level: str = 'INFO',
44
+ cleanup_fp: bool = False,
45
+ ttl: Optional[int] = None
46
+ ):
47
+ """
48
+ 初始化Redis过滤器
49
+
50
+ :param redis_key: Redis中存储指纹的键名
51
+ :param client: Redis客户端实例
52
+ :param stats: 统计信息存储
53
+ :param debug: 是否启用调试模式
54
+ :param log_level: 日志级别
55
+ :param cleanup_fp: 关闭时是否清理指纹
56
+ :param ttl: 指纹过期时间(秒)
57
+ """
58
+ self.logger = get_logger(self.__class__.__name__, log_level)
59
+ super().__init__(self.logger, stats, debug)
60
+
61
+ self.redis_key = redis_key
62
+ self.redis = client
63
+ self.cleanup_fp = cleanup_fp
64
+ self.ttl = ttl
65
+
66
+ # 性能计数器
67
+ self._redis_operations = 0
68
+ self._pipeline_operations = 0
69
+
70
+ @classmethod
71
+ def create_instance(cls, crawler) -> 'BaseFilter':
72
+ """从爬虫配置创建过滤器实例"""
73
+ redis_url = crawler.settings.get('REDIS_URL', 'redis://localhost:6379')
74
+ decode_responses = crawler.settings.get_bool('DECODE_RESPONSES', False)
75
+ ttl_setting = crawler.settings.get_int('REDIS_TTL')
76
+
77
+ # 处理TTL设置
78
+ ttl = None
79
+ if ttl_setting is not None:
80
+ ttl = max(0, int(ttl_setting)) if ttl_setting > 0 else None
81
+
82
+ try:
83
+ redis_client = aioredis.from_url(
84
+ redis_url,
85
+ decode_responses=decode_responses,
86
+ max_connections=20,
87
+ encoding='utf-8'
88
+ )
89
+ except Exception as e:
90
+ raise RuntimeError(f"Redis连接失败: {redis_url} - {str(e)}")
91
+
92
+ return cls(
93
+ redis_key=f"{crawler.settings.get('PROJECT_NAME', 'default')}:{crawler.settings.get('REDIS_KEY', 'request_fingerprints')}",
94
+ client=redis_client,
95
+ stats=crawler.stats,
96
+ cleanup_fp=crawler.settings.get_bool('CLEANUP_FP', False),
97
+ ttl=ttl,
98
+ debug=crawler.settings.get_bool('FILTER_DEBUG', False),
99
+ log_level=crawler.settings.get('LOG_LEVEL', 'INFO')
100
+ )
101
+
102
+ async def requested(self, request) -> bool:
103
+ """
104
+ 检查请求是否已存在(优化版本)
105
+
106
+ :param request: 请求对象
107
+ :return: True 表示重复,False 表示新请求
108
+ """
109
+ try:
110
+ fp = str(request_fingerprint(request))
111
+ self._redis_operations += 1
112
+
113
+ # 使用 pipeline 优化性能
114
+ pipe = self.redis.pipeline()
115
+ pipe.sismember(self.redis_key, fp)
116
+
117
+ results = await pipe.execute()
118
+ exists = results[0]
119
+
120
+ self._pipeline_operations += 1
121
+
122
+ if exists:
123
+ if self.debug:
124
+ self.logger.debug(f"发现重复请求: {fp[:20]}...")
125
+ return True
126
+
127
+ # 如果不存在,添加指纹并设置TTL
128
+ await self.add_fingerprint(fp)
129
+ return False
130
+
131
+ except Exception as e:
132
+ self.logger.error(f"请求检查失败: {getattr(request, 'url', '未知URL')} - {e}")
133
+ # 在网络异常时返回False,避免丢失请求
134
+ return False
135
+
136
+ async def add_fingerprint(self, fp: str) -> bool:
137
+ """
138
+ 添加新指纹到Redis集合(优化版本)
139
+
140
+ :param fp: 请求指纹字符串
141
+ :return: 是否成功添加(True 表示新添加,False 表示已存在)
142
+ """
143
+ try:
144
+ fp = str(fp)
145
+
146
+ # 使用 pipeline 优化性能
147
+ pipe = self.redis.pipeline()
148
+ pipe.sadd(self.redis_key, fp)
149
+
150
+ if self.ttl and self.ttl > 0:
151
+ pipe.expire(self.redis_key, self.ttl)
152
+
153
+ results = await pipe.execute()
154
+ added = results[0] == 1 # sadd 返回 1 表示新添加
155
+
156
+ self._pipeline_operations += 1
157
+
158
+ if self.debug and added:
159
+ self.logger.debug(f"添加新指纹: {fp[:20]}...")
160
+
161
+ return added
162
+
163
+ except Exception as e:
164
+ self.logger.error(f"添加指纹失败: {fp[:20]}... - {e}")
165
+ return False
166
+
167
+ def __contains__(self, item: str) -> bool:
168
+ """
169
+ 同步版本的包含检查(不推荐在异步环境中使用)
170
+
171
+ :param item: 要检查的指纹
172
+ :return: 是否已存在
173
+ """
174
+ # 这是一个同步方法,不能直接调用异步Redis操作
175
+ # 建议使用 requested() 方法替代
176
+ raise NotImplementedError("请使用 requested() 方法进行异步检查")
177
+
178
+ async def get_stats(self) -> dict:
179
+ """获取过滤器详细统计信息"""
180
+ try:
181
+ count = await self.redis.scard(self.redis_key)
182
+
183
+ # 获取TTL信息
184
+ ttl_info = "TTL未设置"
185
+ if self.ttl:
186
+ remaining_ttl = await self.redis.ttl(self.redis_key)
187
+ if remaining_ttl > 0:
188
+ ttl_info = f"剩余 {remaining_ttl} 秒"
189
+ else:
190
+ ttl_info = f"配置 {self.ttl} 秒"
191
+
192
+ stats = {
193
+ 'filter_type': 'AioRedisFilter',
194
+ '指纹总数': count,
195
+ 'Redis键名': self.redis_key,
196
+ 'TTL配置': ttl_info,
197
+ 'Redis操作数': self._redis_operations,
198
+ 'Pipeline操作数': self._pipeline_operations,
199
+ '性能优化率': f"{self._pipeline_operations / max(1, self._redis_operations) * 100:.1f}%"
200
+ }
201
+
202
+ # 合并基类统计
203
+ base_stats = super().get_stats()
204
+ stats.update(base_stats)
205
+
206
+ return stats
207
+
208
+ except Exception as e:
209
+ self.logger.error(f"获取统计信息失败: {e}")
210
+ return super().get_stats()
211
+
212
+ async def clear_all(self) -> int:
213
+ """清空所有指纹数据"""
214
+ try:
215
+ deleted = await self.redis.delete(self.redis_key)
216
+ self.logger.info(f"已清除指纹数: {deleted}")
217
+ return deleted
218
+ except Exception as e:
219
+ self.logger.error("清空指纹失败")
220
+ raise
221
+
222
+ async def closed(self, reason: Optional[str] = None) -> None:
223
+ """爬虫关闭时的清理操作"""
224
+ try:
225
+ if self.cleanup_fp:
226
+ deleted = await self.redis.delete(self.redis_key)
227
+ self.logger.info(f"爬虫关闭清理: 已删除{deleted}个指纹")
228
+ else:
229
+ count = await self.redis.scard(self.redis_key)
230
+ ttl_info = f"{self.ttl}秒" if self.ttl else "持久化"
231
+ self.logger.info(f"保留指纹数: {count} (TTL: {ttl_info})")
232
+ finally:
233
+ await self._close_redis()
234
+
235
+ async def _close_redis(self) -> None:
236
+ """安全关闭Redis连接"""
237
+ try:
238
+ if hasattr(self.redis, 'close'):
239
+ await self.redis.close()
240
+ self.logger.debug("Redis连接已关闭")
241
+ except Exception as e:
242
242
  self.logger.warning(f"Redis关闭时出错:{e}")