crawlo 1.1.3__py3-none-any.whl → 1.1.5__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.
- crawlo/__init__.py +28 -1
- crawlo/__version__.py +1 -1
- crawlo/cleaners/__init__.py +61 -0
- crawlo/cleaners/data_formatter.py +226 -0
- crawlo/cleaners/encoding_converter.py +126 -0
- crawlo/cleaners/text_cleaner.py +233 -0
- crawlo/commands/startproject.py +117 -13
- crawlo/config.py +30 -0
- crawlo/config_validator.py +253 -0
- crawlo/core/engine.py +185 -11
- crawlo/core/scheduler.py +49 -78
- crawlo/crawler.py +6 -6
- crawlo/downloader/__init__.py +24 -0
- crawlo/downloader/aiohttp_downloader.py +8 -0
- crawlo/downloader/cffi_downloader.py +5 -0
- crawlo/downloader/hybrid_downloader.py +214 -0
- crawlo/downloader/playwright_downloader.py +403 -0
- crawlo/downloader/selenium_downloader.py +473 -0
- crawlo/extension/__init__.py +17 -10
- crawlo/extension/health_check.py +142 -0
- crawlo/extension/log_interval.py +27 -18
- crawlo/extension/log_stats.py +62 -24
- crawlo/extension/logging_extension.py +18 -9
- crawlo/extension/memory_monitor.py +105 -0
- crawlo/extension/performance_profiler.py +134 -0
- crawlo/extension/request_recorder.py +108 -0
- crawlo/filters/aioredis_filter.py +50 -12
- crawlo/middleware/proxy.py +26 -2
- crawlo/mode_manager.py +24 -19
- crawlo/network/request.py +30 -3
- crawlo/network/response.py +114 -25
- crawlo/pipelines/mongo_pipeline.py +81 -66
- crawlo/pipelines/mysql_pipeline.py +165 -43
- crawlo/pipelines/redis_dedup_pipeline.py +7 -3
- crawlo/queue/queue_manager.py +15 -2
- crawlo/queue/redis_priority_queue.py +144 -76
- crawlo/settings/default_settings.py +93 -121
- crawlo/subscriber.py +62 -37
- crawlo/templates/project/items.py.tmpl +1 -1
- crawlo/templates/project/middlewares.py.tmpl +73 -49
- crawlo/templates/project/pipelines.py.tmpl +51 -295
- crawlo/templates/project/settings.py.tmpl +93 -17
- crawlo/templates/project/settings_distributed.py.tmpl +120 -0
- crawlo/templates/project/settings_gentle.py.tmpl +95 -0
- crawlo/templates/project/settings_high_performance.py.tmpl +152 -0
- crawlo/templates/project/settings_simple.py.tmpl +69 -0
- crawlo/templates/spider/spider.py.tmpl +2 -38
- crawlo/tools/__init__.py +183 -0
- crawlo/tools/anti_crawler.py +269 -0
- crawlo/tools/authenticated_proxy.py +241 -0
- crawlo/tools/data_validator.py +181 -0
- crawlo/tools/date_tools.py +36 -0
- crawlo/tools/distributed_coordinator.py +387 -0
- crawlo/tools/retry_mechanism.py +221 -0
- crawlo/tools/scenario_adapter.py +263 -0
- crawlo/utils/__init__.py +29 -1
- crawlo/utils/batch_processor.py +261 -0
- crawlo/utils/date_tools.py +58 -1
- crawlo/utils/enhanced_error_handler.py +360 -0
- crawlo/utils/env_config.py +106 -0
- crawlo/utils/error_handler.py +126 -0
- crawlo/utils/performance_monitor.py +285 -0
- crawlo/utils/redis_connection_pool.py +335 -0
- crawlo/utils/redis_key_validator.py +200 -0
- crawlo-1.1.5.dist-info/METADATA +401 -0
- crawlo-1.1.5.dist-info/RECORD +185 -0
- tests/advanced_tools_example.py +276 -0
- tests/authenticated_proxy_example.py +237 -0
- tests/cleaners_example.py +161 -0
- tests/config_validation_demo.py +103 -0
- tests/date_tools_example.py +181 -0
- tests/dynamic_loading_example.py +524 -0
- tests/dynamic_loading_test.py +105 -0
- tests/env_config_example.py +134 -0
- tests/error_handling_example.py +172 -0
- tests/redis_key_validation_demo.py +131 -0
- tests/response_improvements_example.py +145 -0
- tests/test_advanced_tools.py +149 -0
- tests/test_all_redis_key_configs.py +146 -0
- tests/test_authenticated_proxy.py +142 -0
- tests/test_cleaners.py +55 -0
- tests/test_comprehensive.py +147 -0
- tests/test_config_validator.py +194 -0
- tests/test_date_tools.py +124 -0
- tests/test_dynamic_downloaders_proxy.py +125 -0
- tests/test_dynamic_proxy.py +93 -0
- tests/test_dynamic_proxy_config.py +147 -0
- tests/test_dynamic_proxy_real.py +110 -0
- tests/test_edge_cases.py +304 -0
- tests/test_enhanced_error_handler.py +271 -0
- tests/test_env_config.py +122 -0
- tests/test_error_handler_compatibility.py +113 -0
- tests/test_framework_env_usage.py +104 -0
- tests/test_integration.py +357 -0
- tests/test_item_dedup_redis_key.py +123 -0
- tests/test_parsel.py +30 -0
- tests/test_performance.py +328 -0
- tests/test_queue_manager_redis_key.py +177 -0
- tests/test_redis_connection_pool.py +295 -0
- tests/test_redis_key_naming.py +182 -0
- tests/test_redis_key_validator.py +124 -0
- tests/test_response_improvements.py +153 -0
- tests/test_simple_response.py +62 -0
- tests/test_telecom_spider_redis_key.py +206 -0
- tests/test_template_content.py +88 -0
- tests/test_template_redis_key.py +135 -0
- tests/test_tools.py +154 -0
- tests/tools_example.py +258 -0
- crawlo/core/enhanced_engine.py +0 -190
- crawlo-1.1.3.dist-info/METADATA +0 -635
- crawlo-1.1.3.dist-info/RECORD +0 -113
- {crawlo-1.1.3.dist-info → crawlo-1.1.5.dist-info}/WHEEL +0 -0
- {crawlo-1.1.3.dist-info → crawlo-1.1.5.dist-info}/entry_points.txt +0 -0
- {crawlo-1.1.3.dist-info → crawlo-1.1.5.dist-info}/top_level.txt +0 -0
- {examples → tests}/controlled_spider_example.py +0 -0
|
@@ -0,0 +1,285 @@
|
|
|
1
|
+
#!/usr/bin/python
|
|
2
|
+
# -*- coding:UTF-8 -*-
|
|
3
|
+
"""
|
|
4
|
+
性能监控工具
|
|
5
|
+
提供系统性能监控和资源使用情况跟踪
|
|
6
|
+
"""
|
|
7
|
+
import time
|
|
8
|
+
import psutil
|
|
9
|
+
import asyncio
|
|
10
|
+
from typing import Dict, Any, Optional, Callable
|
|
11
|
+
from functools import wraps
|
|
12
|
+
|
|
13
|
+
from crawlo.utils.log import get_logger
|
|
14
|
+
from crawlo.utils.error_handler import ErrorHandler
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class PerformanceMonitor:
|
|
18
|
+
"""性能监控器"""
|
|
19
|
+
|
|
20
|
+
def __init__(self, logger_name: str = __name__):
|
|
21
|
+
self.logger = get_logger(logger_name)
|
|
22
|
+
self.error_handler = ErrorHandler(logger_name)
|
|
23
|
+
self.process = psutil.Process()
|
|
24
|
+
self.start_time = time.time()
|
|
25
|
+
|
|
26
|
+
# 性能指标
|
|
27
|
+
self.metrics = {
|
|
28
|
+
'cpu_usage': [],
|
|
29
|
+
'memory_usage': [],
|
|
30
|
+
'network_io': [],
|
|
31
|
+
'disk_io': []
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
def get_system_metrics(self) -> Dict[str, Any]:
|
|
35
|
+
"""
|
|
36
|
+
获取系统性能指标
|
|
37
|
+
|
|
38
|
+
Returns:
|
|
39
|
+
包含各种性能指标的字典
|
|
40
|
+
"""
|
|
41
|
+
try:
|
|
42
|
+
# CPU使用率
|
|
43
|
+
cpu_percent = psutil.cpu_percent(interval=1)
|
|
44
|
+
|
|
45
|
+
# 内存使用情况
|
|
46
|
+
memory = psutil.virtual_memory()
|
|
47
|
+
|
|
48
|
+
# 网络IO
|
|
49
|
+
net_io = psutil.net_io_counters()
|
|
50
|
+
|
|
51
|
+
# 磁盘IO
|
|
52
|
+
disk_io = psutil.disk_io_counters()
|
|
53
|
+
|
|
54
|
+
# 进程特定信息
|
|
55
|
+
process_memory = self.process.memory_info()
|
|
56
|
+
process_cpu = self.process.cpu_percent()
|
|
57
|
+
|
|
58
|
+
return {
|
|
59
|
+
'timestamp': time.time(),
|
|
60
|
+
'uptime': time.time() - self.start_time,
|
|
61
|
+
'cpu': {
|
|
62
|
+
'percent': cpu_percent,
|
|
63
|
+
'count': psutil.cpu_count(),
|
|
64
|
+
'freq': psutil.cpu_freq()._asdict() if psutil.cpu_freq() else {}
|
|
65
|
+
},
|
|
66
|
+
'memory': {
|
|
67
|
+
'total': memory.total,
|
|
68
|
+
'available': memory.available,
|
|
69
|
+
'percent': memory.percent,
|
|
70
|
+
'used': memory.used,
|
|
71
|
+
'free': memory.free
|
|
72
|
+
},
|
|
73
|
+
'process': {
|
|
74
|
+
'memory_rss': process_memory.rss,
|
|
75
|
+
'memory_vms': process_memory.vms,
|
|
76
|
+
'cpu_percent': process_cpu,
|
|
77
|
+
'num_threads': self.process.num_threads(),
|
|
78
|
+
'num_fds': self.process.num_fds() if hasattr(self.process, 'num_fds') else 0
|
|
79
|
+
},
|
|
80
|
+
'network': {
|
|
81
|
+
'bytes_sent': net_io.bytes_sent,
|
|
82
|
+
'bytes_recv': net_io.bytes_recv,
|
|
83
|
+
'packets_sent': net_io.packets_sent,
|
|
84
|
+
'packets_recv': net_io.packets_recv
|
|
85
|
+
},
|
|
86
|
+
'disk': {
|
|
87
|
+
'read_bytes': disk_io.read_bytes,
|
|
88
|
+
'write_bytes': disk_io.write_bytes,
|
|
89
|
+
'read_count': disk_io.read_count,
|
|
90
|
+
'write_count': disk_io.write_count
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
except Exception as e:
|
|
94
|
+
self.error_handler.handle_error(
|
|
95
|
+
e,
|
|
96
|
+
context="获取系统性能指标失败",
|
|
97
|
+
raise_error=False
|
|
98
|
+
)
|
|
99
|
+
return {}
|
|
100
|
+
|
|
101
|
+
def log_system_metrics(self, detailed: bool = False):
|
|
102
|
+
"""
|
|
103
|
+
记录系统性能指标
|
|
104
|
+
|
|
105
|
+
Args:
|
|
106
|
+
detailed: 是否记录详细信息
|
|
107
|
+
"""
|
|
108
|
+
try:
|
|
109
|
+
metrics = self.get_system_metrics()
|
|
110
|
+
if not metrics:
|
|
111
|
+
return
|
|
112
|
+
|
|
113
|
+
# 基本信息
|
|
114
|
+
basic_info = (
|
|
115
|
+
f"📊 系统性能指标 | "
|
|
116
|
+
f"CPU: {metrics['cpu']['percent']:.1f}% | "
|
|
117
|
+
f"内存: {metrics['memory']['percent']:.1f}% | "
|
|
118
|
+
f"进程CPU: {metrics['process']['cpu_percent']:.1f}% | "
|
|
119
|
+
f"进程内存: {metrics['process']['memory_rss'] / 1024 / 1024:.1f}MB"
|
|
120
|
+
)
|
|
121
|
+
self.logger.info(basic_info)
|
|
122
|
+
|
|
123
|
+
# 详细信息
|
|
124
|
+
if detailed:
|
|
125
|
+
detailed_info = (
|
|
126
|
+
f" 详细信息:\n"
|
|
127
|
+
f" - CPU: {metrics['cpu']['count']} 核心\n"
|
|
128
|
+
f" - 内存: 总计 {metrics['memory']['total'] / 1024 / 1024 / 1024:.1f}GB, "
|
|
129
|
+
f"可用 {metrics['memory']['available'] / 1024 / 1024 / 1024:.1f}GB\n"
|
|
130
|
+
f" - 网络: 发送 {metrics['network']['bytes_sent'] / 1024 / 1024:.1f}MB, "
|
|
131
|
+
f"接收 {metrics['network']['bytes_recv'] / 1024 / 1024:.1f}MB\n"
|
|
132
|
+
f" - 磁盘: 读取 {metrics['disk']['read_bytes'] / 1024 / 1024:.1f}MB, "
|
|
133
|
+
f"写入 {metrics['disk']['write_bytes'] / 1024 / 1024:.1f}MB"
|
|
134
|
+
)
|
|
135
|
+
self.logger.debug(detailed_info)
|
|
136
|
+
except Exception as e:
|
|
137
|
+
self.error_handler.handle_error(
|
|
138
|
+
e,
|
|
139
|
+
context="记录系统性能指标失败",
|
|
140
|
+
raise_error=False
|
|
141
|
+
)
|
|
142
|
+
|
|
143
|
+
def start_monitoring(self, interval: int = 60, detailed: bool = False):
|
|
144
|
+
"""
|
|
145
|
+
开始定期监控
|
|
146
|
+
|
|
147
|
+
Args:
|
|
148
|
+
interval: 监控间隔(秒)
|
|
149
|
+
detailed: 是否记录详细信息
|
|
150
|
+
"""
|
|
151
|
+
async def monitor_loop():
|
|
152
|
+
while True:
|
|
153
|
+
try:
|
|
154
|
+
self.log_system_metrics(detailed)
|
|
155
|
+
await asyncio.sleep(interval)
|
|
156
|
+
except asyncio.CancelledError:
|
|
157
|
+
break
|
|
158
|
+
except Exception as e:
|
|
159
|
+
self.logger.error(f"监控循环错误: {e}")
|
|
160
|
+
|
|
161
|
+
# 启动监控任务
|
|
162
|
+
self.monitor_task = asyncio.create_task(monitor_loop())
|
|
163
|
+
self.logger.info(f"开始性能监控,间隔: {interval}秒")
|
|
164
|
+
|
|
165
|
+
async def stop_monitoring(self):
|
|
166
|
+
"""停止监控"""
|
|
167
|
+
if hasattr(self, 'monitor_task') and self.monitor_task:
|
|
168
|
+
self.monitor_task.cancel()
|
|
169
|
+
try:
|
|
170
|
+
await self.monitor_task
|
|
171
|
+
except asyncio.CancelledError:
|
|
172
|
+
pass
|
|
173
|
+
self.logger.info("性能监控已停止")
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
class PerformanceTimer:
|
|
177
|
+
"""性能计时器"""
|
|
178
|
+
|
|
179
|
+
def __init__(self, name: str = "timer"):
|
|
180
|
+
self.name = name
|
|
181
|
+
self.start_time = None
|
|
182
|
+
self.end_time = None
|
|
183
|
+
self.logger = get_logger(f"{__name__}.{self.__class__.__name__}")
|
|
184
|
+
self.error_handler = ErrorHandler(f"{__name__}.{self.__class__.__name__}")
|
|
185
|
+
|
|
186
|
+
def start(self):
|
|
187
|
+
"""开始计时"""
|
|
188
|
+
self.start_time = time.time()
|
|
189
|
+
self.logger.debug(f"⏱️ 开始计时: {self.name}")
|
|
190
|
+
|
|
191
|
+
def stop(self) -> float:
|
|
192
|
+
"""
|
|
193
|
+
停止计时并返回耗时
|
|
194
|
+
|
|
195
|
+
Returns:
|
|
196
|
+
耗时(秒)
|
|
197
|
+
"""
|
|
198
|
+
self.end_time = time.time()
|
|
199
|
+
if self.start_time is None:
|
|
200
|
+
raise RuntimeError("计时器未启动")
|
|
201
|
+
|
|
202
|
+
elapsed = self.end_time - self.start_time
|
|
203
|
+
self.logger.debug(f"⏱️ 停止计时: {self.name}, 耗时: {elapsed:.3f}秒")
|
|
204
|
+
return elapsed
|
|
205
|
+
|
|
206
|
+
def __enter__(self):
|
|
207
|
+
self.start()
|
|
208
|
+
return self
|
|
209
|
+
|
|
210
|
+
def __exit__(self, exc_type, exc_val, exc_tb):
|
|
211
|
+
try:
|
|
212
|
+
elapsed = self.stop()
|
|
213
|
+
if exc_type is None:
|
|
214
|
+
self.logger.info(f"✅ {self.name} 执行成功,耗时: {elapsed:.3f}秒")
|
|
215
|
+
else:
|
|
216
|
+
self.logger.error(f"❌ {self.name} 执行失败,耗时: {elapsed:.3f}秒")
|
|
217
|
+
except Exception as e:
|
|
218
|
+
self.error_handler.handle_error(
|
|
219
|
+
e,
|
|
220
|
+
context=f"计时器退出时发生错误: {self.name}",
|
|
221
|
+
raise_error=False
|
|
222
|
+
)
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def performance_monitor_decorator(name: str = None, log_level: str = "INFO"):
|
|
226
|
+
"""
|
|
227
|
+
装饰器:监控函数性能
|
|
228
|
+
|
|
229
|
+
Args:
|
|
230
|
+
name: 函数名称(如果为None则使用函数名)
|
|
231
|
+
log_level: 日志级别
|
|
232
|
+
"""
|
|
233
|
+
def decorator(func):
|
|
234
|
+
@wraps(func)
|
|
235
|
+
async def async_wrapper(*args, **kwargs):
|
|
236
|
+
timer_name = name or f"{func.__module__}.{func.__name__}"
|
|
237
|
+
logger = get_logger(timer_name)
|
|
238
|
+
|
|
239
|
+
with PerformanceTimer(timer_name) as timer:
|
|
240
|
+
if asyncio.iscoroutinefunction(func):
|
|
241
|
+
return await func(*args, **kwargs)
|
|
242
|
+
else:
|
|
243
|
+
return func(*args, **kwargs)
|
|
244
|
+
|
|
245
|
+
@wraps(func)
|
|
246
|
+
def sync_wrapper(*args, **kwargs):
|
|
247
|
+
timer_name = name or f"{func.__module__}.{func.__name__}"
|
|
248
|
+
logger = get_logger(timer_name)
|
|
249
|
+
|
|
250
|
+
with PerformanceTimer(timer_name) as timer:
|
|
251
|
+
return func(*args, **kwargs)
|
|
252
|
+
|
|
253
|
+
# 根据函数是否为异步函数返回相应的包装器
|
|
254
|
+
import inspect
|
|
255
|
+
if inspect.iscoroutinefunction(func):
|
|
256
|
+
return async_wrapper
|
|
257
|
+
else:
|
|
258
|
+
return sync_wrapper
|
|
259
|
+
|
|
260
|
+
return decorator
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
# 全局性能监控器实例
|
|
264
|
+
default_performance_monitor = PerformanceMonitor()
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def monitor_performance(interval: int = 60, detailed: bool = False):
|
|
268
|
+
"""
|
|
269
|
+
便捷函数:开始性能监控
|
|
270
|
+
|
|
271
|
+
Args:
|
|
272
|
+
interval: 监控间隔(秒)
|
|
273
|
+
detailed: 是否记录详细信息
|
|
274
|
+
"""
|
|
275
|
+
default_performance_monitor.start_monitoring(interval, detailed)
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def get_current_metrics() -> Dict[str, Any]:
|
|
279
|
+
"""
|
|
280
|
+
便捷函数:获取当前性能指标
|
|
281
|
+
|
|
282
|
+
Returns:
|
|
283
|
+
性能指标字典
|
|
284
|
+
"""
|
|
285
|
+
return default_performance_monitor.get_system_metrics()
|
|
@@ -0,0 +1,335 @@
|
|
|
1
|
+
#!/usr/bin/python
|
|
2
|
+
# -*- coding:UTF-8 -*-
|
|
3
|
+
"""
|
|
4
|
+
Redis连接池优化工具
|
|
5
|
+
提供优化的Redis连接池管理和配置
|
|
6
|
+
"""
|
|
7
|
+
import asyncio
|
|
8
|
+
import redis.asyncio as aioredis
|
|
9
|
+
from typing import Dict, Any, Optional, Union
|
|
10
|
+
from contextlib import asynccontextmanager
|
|
11
|
+
|
|
12
|
+
from crawlo.utils.log import get_logger
|
|
13
|
+
from crawlo.utils.error_handler import ErrorHandler
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class OptimizedRedisConnectionPool:
|
|
17
|
+
"""优化的Redis连接池管理器"""
|
|
18
|
+
|
|
19
|
+
# 默认连接池配置
|
|
20
|
+
DEFAULT_CONFIG = {
|
|
21
|
+
'max_connections': 50,
|
|
22
|
+
'socket_connect_timeout': 5,
|
|
23
|
+
'socket_timeout': 30,
|
|
24
|
+
'socket_keepalive': True,
|
|
25
|
+
'health_check_interval': 30,
|
|
26
|
+
'retry_on_timeout': True,
|
|
27
|
+
'encoding': 'utf-8',
|
|
28
|
+
'decode_responses': False,
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
def __init__(self, redis_url: str, **kwargs):
|
|
32
|
+
self.redis_url = redis_url
|
|
33
|
+
self.config = {**self.DEFAULT_CONFIG, **kwargs}
|
|
34
|
+
self.logger = get_logger(self.__class__.__name__)
|
|
35
|
+
self.error_handler = ErrorHandler(self.__class__.__name__)
|
|
36
|
+
|
|
37
|
+
# 连接池实例
|
|
38
|
+
self._connection_pool: Optional[aioredis.ConnectionPool] = None
|
|
39
|
+
self._redis_client: Optional[aioredis.Redis] = None
|
|
40
|
+
|
|
41
|
+
# 连接池统计信息
|
|
42
|
+
self._stats = {
|
|
43
|
+
'created_connections': 0,
|
|
44
|
+
'active_connections': 0,
|
|
45
|
+
'idle_connections': 0,
|
|
46
|
+
'errors': 0
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
# 初始化连接池
|
|
50
|
+
self._initialize_pool()
|
|
51
|
+
|
|
52
|
+
def _initialize_pool(self):
|
|
53
|
+
"""初始化连接池"""
|
|
54
|
+
try:
|
|
55
|
+
self._connection_pool = aioredis.ConnectionPool.from_url(
|
|
56
|
+
self.redis_url,
|
|
57
|
+
**self.config
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
self._redis_client = aioredis.Redis(
|
|
61
|
+
connection_pool=self._connection_pool
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
self.logger.info(f"✅ Redis连接池初始化成功: {self.redis_url}")
|
|
65
|
+
self.logger.debug(f" 连接池配置: {self.config}")
|
|
66
|
+
|
|
67
|
+
except Exception as e:
|
|
68
|
+
self.error_handler.handle_error(
|
|
69
|
+
e,
|
|
70
|
+
context="Redis连接池初始化失败",
|
|
71
|
+
raise_error=True
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
async def get_connection(self) -> aioredis.Redis:
|
|
75
|
+
"""
|
|
76
|
+
获取Redis连接实例
|
|
77
|
+
|
|
78
|
+
Returns:
|
|
79
|
+
Redis连接实例
|
|
80
|
+
"""
|
|
81
|
+
if not self._redis_client:
|
|
82
|
+
await self._initialize_pool()
|
|
83
|
+
|
|
84
|
+
self._stats['active_connections'] += 1
|
|
85
|
+
return self._redis_client
|
|
86
|
+
|
|
87
|
+
async def ping(self) -> bool:
|
|
88
|
+
"""
|
|
89
|
+
检查Redis连接是否正常
|
|
90
|
+
|
|
91
|
+
Returns:
|
|
92
|
+
连接是否正常
|
|
93
|
+
"""
|
|
94
|
+
try:
|
|
95
|
+
if self._redis_client:
|
|
96
|
+
await self._redis_client.ping()
|
|
97
|
+
return True
|
|
98
|
+
return False
|
|
99
|
+
except Exception as e:
|
|
100
|
+
self.logger.warning(f"Redis连接检查失败: {e}")
|
|
101
|
+
return False
|
|
102
|
+
|
|
103
|
+
async def close(self):
|
|
104
|
+
"""关闭连接池"""
|
|
105
|
+
try:
|
|
106
|
+
if self._redis_client:
|
|
107
|
+
await self._redis_client.close()
|
|
108
|
+
self._redis_client = None
|
|
109
|
+
|
|
110
|
+
if self._connection_pool:
|
|
111
|
+
await self._connection_pool.disconnect()
|
|
112
|
+
self._connection_pool = None
|
|
113
|
+
|
|
114
|
+
self.logger.info("✅ Redis连接池已关闭")
|
|
115
|
+
except Exception as e:
|
|
116
|
+
self.error_handler.handle_error(
|
|
117
|
+
e,
|
|
118
|
+
context="关闭Redis连接池失败",
|
|
119
|
+
raise_error=False
|
|
120
|
+
)
|
|
121
|
+
|
|
122
|
+
def get_stats(self) -> Dict[str, Any]:
|
|
123
|
+
"""
|
|
124
|
+
获取连接池统计信息
|
|
125
|
+
|
|
126
|
+
Returns:
|
|
127
|
+
统计信息字典
|
|
128
|
+
"""
|
|
129
|
+
if self._connection_pool:
|
|
130
|
+
pool_stats = {
|
|
131
|
+
'max_connections': self._connection_pool.max_connections,
|
|
132
|
+
'created_connections': self._connection_pool.created_connections,
|
|
133
|
+
'available_connections': len(self._connection_pool._available_connections),
|
|
134
|
+
'in_use_connections': len(self._connection_pool._in_use_connections),
|
|
135
|
+
}
|
|
136
|
+
self._stats.update(pool_stats)
|
|
137
|
+
|
|
138
|
+
return self._stats.copy()
|
|
139
|
+
|
|
140
|
+
@asynccontextmanager
|
|
141
|
+
async def connection_context(self):
|
|
142
|
+
"""
|
|
143
|
+
连接上下文管理器
|
|
144
|
+
|
|
145
|
+
Yields:
|
|
146
|
+
Redis连接实例
|
|
147
|
+
"""
|
|
148
|
+
connection = await self.get_connection()
|
|
149
|
+
try:
|
|
150
|
+
yield connection
|
|
151
|
+
finally:
|
|
152
|
+
self._stats['active_connections'] -= 1
|
|
153
|
+
self._stats['idle_connections'] += 1
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
class RedisBatchOperationHelper:
|
|
157
|
+
"""Redis批量操作助手"""
|
|
158
|
+
|
|
159
|
+
def __init__(self, redis_client: aioredis.Redis, batch_size: int = 100):
|
|
160
|
+
self.redis_client = redis_client
|
|
161
|
+
self.batch_size = batch_size
|
|
162
|
+
self.logger = get_logger(self.__class__.__name__)
|
|
163
|
+
self.error_handler = ErrorHandler(self.__class__.__name__)
|
|
164
|
+
|
|
165
|
+
async def batch_execute(self, operations: list, batch_size: Optional[int] = None) -> list:
|
|
166
|
+
"""
|
|
167
|
+
批量执行Redis操作
|
|
168
|
+
|
|
169
|
+
Args:
|
|
170
|
+
operations: 操作列表,每个操作是一个包含(command, *args)的元组
|
|
171
|
+
batch_size: 批次大小(如果为None则使用实例的batch_size)
|
|
172
|
+
|
|
173
|
+
Returns:
|
|
174
|
+
执行结果列表
|
|
175
|
+
"""
|
|
176
|
+
actual_batch_size = batch_size or self.batch_size
|
|
177
|
+
results = []
|
|
178
|
+
|
|
179
|
+
try:
|
|
180
|
+
for i in range(0, len(operations), actual_batch_size):
|
|
181
|
+
batch = operations[i:i + actual_batch_size]
|
|
182
|
+
self.logger.debug(f"执行批次 {i//actual_batch_size + 1}/{(len(operations)-1)//actual_batch_size + 1}")
|
|
183
|
+
|
|
184
|
+
try:
|
|
185
|
+
pipe = self.redis_client.pipeline()
|
|
186
|
+
for operation in batch:
|
|
187
|
+
command, *args = operation
|
|
188
|
+
getattr(pipe, command)(*args)
|
|
189
|
+
|
|
190
|
+
batch_results = await pipe.execute()
|
|
191
|
+
results.extend(batch_results)
|
|
192
|
+
|
|
193
|
+
except Exception as e:
|
|
194
|
+
self.logger.error(f"执行批次失败: {e}")
|
|
195
|
+
# 继续执行下一个批次而不是中断
|
|
196
|
+
|
|
197
|
+
except Exception as e:
|
|
198
|
+
self.error_handler.handle_error(
|
|
199
|
+
e,
|
|
200
|
+
context="Redis批量操作执行失败",
|
|
201
|
+
raise_error=False
|
|
202
|
+
)
|
|
203
|
+
|
|
204
|
+
return results
|
|
205
|
+
|
|
206
|
+
async def batch_set_hash(self, hash_key: str, items: Dict[str, Any]) -> int:
|
|
207
|
+
"""
|
|
208
|
+
批量设置Hash字段
|
|
209
|
+
|
|
210
|
+
Args:
|
|
211
|
+
hash_key: Hash键名
|
|
212
|
+
items: 要设置的字段字典
|
|
213
|
+
|
|
214
|
+
Returns:
|
|
215
|
+
成功设置的字段数量
|
|
216
|
+
"""
|
|
217
|
+
try:
|
|
218
|
+
if not items:
|
|
219
|
+
return 0
|
|
220
|
+
|
|
221
|
+
pipe = self.redis_client.pipeline()
|
|
222
|
+
count = 0
|
|
223
|
+
|
|
224
|
+
for key, value in items.items():
|
|
225
|
+
pipe.hset(hash_key, key, value)
|
|
226
|
+
count += 1
|
|
227
|
+
|
|
228
|
+
# 每达到批次大小就执行一次
|
|
229
|
+
if count % self.batch_size == 0:
|
|
230
|
+
await pipe.execute()
|
|
231
|
+
pipe = self.redis_client.pipeline()
|
|
232
|
+
|
|
233
|
+
# 执行剩余的操作
|
|
234
|
+
if count % self.batch_size != 0:
|
|
235
|
+
await pipe.execute()
|
|
236
|
+
|
|
237
|
+
self.logger.debug(f"批量设置Hash {count} 个字段")
|
|
238
|
+
return count
|
|
239
|
+
|
|
240
|
+
except Exception as e:
|
|
241
|
+
self.error_handler.handle_error(
|
|
242
|
+
e,
|
|
243
|
+
context="Redis批量设置Hash失败",
|
|
244
|
+
raise_error=False
|
|
245
|
+
)
|
|
246
|
+
return 0
|
|
247
|
+
|
|
248
|
+
async def batch_get_hash(self, hash_key: str, fields: list) -> Dict[str, Any]:
|
|
249
|
+
"""
|
|
250
|
+
批量获取Hash字段值
|
|
251
|
+
|
|
252
|
+
Args:
|
|
253
|
+
hash_key: Hash键名
|
|
254
|
+
fields: 要获取的字段列表
|
|
255
|
+
|
|
256
|
+
Returns:
|
|
257
|
+
字段值字典
|
|
258
|
+
"""
|
|
259
|
+
try:
|
|
260
|
+
if not fields:
|
|
261
|
+
return {}
|
|
262
|
+
|
|
263
|
+
# 使用管道批量获取
|
|
264
|
+
pipe = self.redis_client.pipeline()
|
|
265
|
+
for field in fields:
|
|
266
|
+
pipe.hget(hash_key, field)
|
|
267
|
+
|
|
268
|
+
results = await pipe.execute()
|
|
269
|
+
|
|
270
|
+
# 构建结果字典
|
|
271
|
+
result_dict = {}
|
|
272
|
+
for i, field in enumerate(fields):
|
|
273
|
+
if results[i] is not None:
|
|
274
|
+
result_dict[field] = results[i]
|
|
275
|
+
|
|
276
|
+
self.logger.debug(f"批量获取Hash {len(result_dict)} 个字段")
|
|
277
|
+
return result_dict
|
|
278
|
+
|
|
279
|
+
except Exception as e:
|
|
280
|
+
self.error_handler.handle_error(
|
|
281
|
+
e,
|
|
282
|
+
context="Redis批量获取Hash失败",
|
|
283
|
+
raise_error=False
|
|
284
|
+
)
|
|
285
|
+
return {}
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
# 全局连接池管理器
|
|
289
|
+
_connection_pools: Dict[str, OptimizedRedisConnectionPool] = {}
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def get_redis_pool(redis_url: str, **kwargs) -> OptimizedRedisConnectionPool:
|
|
293
|
+
"""
|
|
294
|
+
获取Redis连接池实例(单例模式)
|
|
295
|
+
|
|
296
|
+
Args:
|
|
297
|
+
redis_url: Redis URL
|
|
298
|
+
**kwargs: 连接池配置参数
|
|
299
|
+
|
|
300
|
+
Returns:
|
|
301
|
+
Redis连接池实例
|
|
302
|
+
"""
|
|
303
|
+
if redis_url not in _connection_pools:
|
|
304
|
+
_connection_pools[redis_url] = OptimizedRedisConnectionPool(redis_url, **kwargs)
|
|
305
|
+
|
|
306
|
+
return _connection_pools[redis_url]
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
async def close_all_pools():
|
|
310
|
+
"""关闭所有连接池"""
|
|
311
|
+
global _connection_pools
|
|
312
|
+
|
|
313
|
+
for pool in _connection_pools.values():
|
|
314
|
+
await pool.close()
|
|
315
|
+
|
|
316
|
+
_connection_pools.clear()
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
# 便捷函数
|
|
320
|
+
async def execute_redis_batch(redis_url: str, operations: list, batch_size: int = 100) -> list:
|
|
321
|
+
"""
|
|
322
|
+
便捷函数:执行Redis批量操作
|
|
323
|
+
|
|
324
|
+
Args:
|
|
325
|
+
redis_url: Redis URL
|
|
326
|
+
operations: 操作列表
|
|
327
|
+
batch_size: 批次大小
|
|
328
|
+
|
|
329
|
+
Returns:
|
|
330
|
+
执行结果列表
|
|
331
|
+
"""
|
|
332
|
+
pool = get_redis_pool(redis_url)
|
|
333
|
+
redis_client = await pool.get_connection()
|
|
334
|
+
helper = RedisBatchOperationHelper(redis_client, batch_size)
|
|
335
|
+
return await helper.batch_execute(operations)
|