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.
- crawlo/__init__.py +34 -34
- crawlo/__version__.py +1 -1
- crawlo/cli.py +40 -40
- crawlo/commands/__init__.py +13 -13
- crawlo/commands/check.py +594 -594
- crawlo/commands/genspider.py +151 -151
- crawlo/commands/list.py +155 -155
- crawlo/commands/run.py +285 -285
- crawlo/commands/startproject.py +196 -196
- crawlo/commands/stats.py +188 -188
- crawlo/commands/utils.py +186 -186
- crawlo/config.py +279 -279
- crawlo/core/__init__.py +2 -2
- crawlo/core/engine.py +171 -171
- crawlo/core/enhanced_engine.py +189 -189
- crawlo/core/processor.py +40 -40
- crawlo/core/scheduler.py +165 -165
- crawlo/crawler.py +1027 -1027
- crawlo/downloader/__init__.py +242 -242
- crawlo/downloader/aiohttp_downloader.py +212 -212
- crawlo/downloader/cffi_downloader.py +251 -251
- crawlo/downloader/httpx_downloader.py +259 -259
- crawlo/event.py +11 -11
- crawlo/exceptions.py +81 -81
- crawlo/extension/__init__.py +38 -31
- crawlo/extension/health_check.py +142 -0
- crawlo/extension/log_interval.py +58 -49
- crawlo/extension/log_stats.py +82 -44
- crawlo/extension/logging_extension.py +44 -35
- crawlo/extension/memory_monitor.py +89 -0
- crawlo/extension/performance_profiler.py +118 -0
- crawlo/extension/request_recorder.py +108 -0
- crawlo/filters/__init__.py +154 -154
- crawlo/filters/aioredis_filter.py +241 -241
- crawlo/filters/memory_filter.py +269 -269
- crawlo/items/__init__.py +23 -23
- crawlo/items/base.py +21 -21
- crawlo/items/fields.py +53 -53
- crawlo/items/items.py +104 -104
- crawlo/middleware/__init__.py +21 -21
- crawlo/middleware/default_header.py +32 -32
- crawlo/middleware/download_delay.py +28 -28
- crawlo/middleware/middleware_manager.py +135 -135
- crawlo/middleware/proxy.py +248 -248
- crawlo/middleware/request_ignore.py +30 -30
- crawlo/middleware/response_code.py +18 -18
- crawlo/middleware/response_filter.py +26 -26
- crawlo/middleware/retry.py +124 -124
- crawlo/mode_manager.py +200 -200
- crawlo/network/__init__.py +21 -21
- crawlo/network/request.py +311 -311
- crawlo/network/response.py +271 -271
- crawlo/pipelines/__init__.py +21 -21
- crawlo/pipelines/bloom_dedup_pipeline.py +156 -156
- crawlo/pipelines/console_pipeline.py +39 -39
- crawlo/pipelines/csv_pipeline.py +316 -316
- crawlo/pipelines/database_dedup_pipeline.py +224 -224
- crawlo/pipelines/json_pipeline.py +218 -218
- crawlo/pipelines/memory_dedup_pipeline.py +115 -115
- crawlo/pipelines/mongo_pipeline.py +132 -117
- crawlo/pipelines/mysql_pipeline.py +317 -195
- crawlo/pipelines/pipeline_manager.py +56 -56
- crawlo/pipelines/redis_dedup_pipeline.py +162 -162
- crawlo/project.py +153 -153
- crawlo/queue/pqueue.py +37 -37
- crawlo/queue/queue_manager.py +307 -307
- crawlo/queue/redis_priority_queue.py +208 -208
- crawlo/settings/__init__.py +7 -7
- crawlo/settings/default_settings.py +278 -244
- crawlo/settings/setting_manager.py +99 -99
- crawlo/spider/__init__.py +639 -639
- crawlo/stats_collector.py +59 -59
- crawlo/subscriber.py +131 -106
- crawlo/task_manager.py +30 -30
- crawlo/templates/crawlo.cfg.tmpl +10 -10
- crawlo/templates/project/__init__.py.tmpl +3 -3
- crawlo/templates/project/items.py.tmpl +17 -17
- crawlo/templates/project/middlewares.py.tmpl +111 -87
- crawlo/templates/project/pipelines.py.tmpl +97 -341
- crawlo/templates/project/run.py.tmpl +251 -251
- crawlo/templates/project/settings.py.tmpl +279 -250
- crawlo/templates/project/spiders/__init__.py.tmpl +5 -5
- crawlo/templates/spider/spider.py.tmpl +142 -178
- crawlo/utils/__init__.py +7 -7
- crawlo/utils/controlled_spider_mixin.py +439 -439
- crawlo/utils/date_tools.py +233 -233
- crawlo/utils/db_helper.py +343 -343
- crawlo/utils/func_tools.py +82 -82
- crawlo/utils/large_scale_config.py +286 -286
- crawlo/utils/large_scale_helper.py +343 -343
- crawlo/utils/log.py +128 -128
- crawlo/utils/queue_helper.py +175 -175
- crawlo/utils/request.py +267 -267
- crawlo/utils/request_serializer.py +219 -219
- crawlo/utils/spider_loader.py +62 -62
- crawlo/utils/system.py +11 -11
- crawlo/utils/tools.py +4 -4
- crawlo/utils/url.py +39 -39
- crawlo-1.1.4.dist-info/METADATA +403 -0
- crawlo-1.1.4.dist-info/RECORD +117 -0
- examples/__init__.py +7 -7
- examples/controlled_spider_example.py +205 -205
- tests/__init__.py +7 -7
- tests/test_final_validation.py +153 -153
- tests/test_proxy_health_check.py +32 -32
- tests/test_proxy_middleware_integration.py +136 -136
- tests/test_proxy_providers.py +56 -56
- tests/test_proxy_stats.py +19 -19
- tests/test_proxy_strategies.py +59 -59
- tests/test_redis_config.py +28 -28
- tests/test_redis_queue.py +224 -224
- tests/test_request_serialization.py +70 -70
- tests/test_scheduler.py +241 -241
- 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.4.dist-info}/WHEEL +0 -0
- {crawlo-1.1.3.dist-info → crawlo-1.1.4.dist-info}/entry_points.txt +0 -0
- {crawlo-1.1.3.dist-info → crawlo-1.1.4.dist-info}/top_level.txt +0 -0
|
@@ -1,209 +1,209 @@
|
|
|
1
|
-
import pickle
|
|
2
|
-
import time
|
|
3
|
-
import asyncio
|
|
4
|
-
from typing import Optional
|
|
5
|
-
import redis.asyncio as aioredis
|
|
6
|
-
import traceback
|
|
7
|
-
import os
|
|
8
|
-
|
|
9
|
-
from crawlo import Request
|
|
10
|
-
from crawlo.utils.log import get_logger
|
|
11
|
-
from crawlo.utils.request_serializer import RequestSerializer
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
logger = get_logger(__name__)
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
class RedisPriorityQueue:
|
|
18
|
-
"""
|
|
19
|
-
基于 Redis 的分布式异步优先级队列(生产级优化版)
|
|
20
|
-
"""
|
|
21
|
-
|
|
22
|
-
def __init__(
|
|
23
|
-
self,
|
|
24
|
-
redis_url: str = None,
|
|
25
|
-
queue_name: str = "crawlo:requests",
|
|
26
|
-
processing_queue: str = "crawlo:processing",
|
|
27
|
-
failed_queue: str = "crawlo:failed",
|
|
28
|
-
max_retries: int = 3,
|
|
29
|
-
timeout: int = 300, # 任务处理超时时间(秒)
|
|
30
|
-
max_connections: int = 10, # 连接池大小
|
|
31
|
-
):
|
|
32
|
-
# 如果没有提供 redis_url,则从环境变量构造
|
|
33
|
-
if redis_url is None:
|
|
34
|
-
redis_host = os.getenv('REDIS_HOST', 'localhost')
|
|
35
|
-
redis_port = os.getenv('REDIS_PORT', '6379')
|
|
36
|
-
redis_db = os.getenv('REDIS_DB', '0')
|
|
37
|
-
redis_password = os.getenv('REDIS_PASSWORD', '')
|
|
38
|
-
|
|
39
|
-
if redis_password:
|
|
40
|
-
redis_url = f"redis://:{redis_password}@{redis_host}:{redis_port}/{redis_db}"
|
|
41
|
-
else:
|
|
42
|
-
redis_url = f"redis://{redis_host}:{redis_port}/{redis_db}"
|
|
43
|
-
|
|
44
|
-
self.redis_url = redis_url
|
|
45
|
-
self.queue_name = queue_name
|
|
46
|
-
self.processing_queue = processing_queue
|
|
47
|
-
self.failed_queue = failed_queue
|
|
48
|
-
self.max_retries = max_retries
|
|
49
|
-
self.timeout = timeout
|
|
50
|
-
self.max_connections = max_connections
|
|
51
|
-
self._redis = None
|
|
52
|
-
self._lock = asyncio.Lock() # 用于连接初始化的锁
|
|
53
|
-
self.request_serializer = RequestSerializer() # 处理序列化
|
|
54
|
-
|
|
55
|
-
async def connect(self, max_retries=3, delay=1):
|
|
56
|
-
"""异步连接 Redis,支持重试"""
|
|
57
|
-
async with self._lock:
|
|
58
|
-
if self._redis is not None:
|
|
59
|
-
return self._redis
|
|
60
|
-
|
|
61
|
-
for attempt in range(max_retries):
|
|
62
|
-
try:
|
|
63
|
-
self._redis = await aioredis.from_url(
|
|
64
|
-
self.redis_url,
|
|
65
|
-
decode_responses=False, # pickle 需要 bytes
|
|
66
|
-
max_connections=self.max_connections,
|
|
67
|
-
socket_connect_timeout=5,
|
|
68
|
-
socket_timeout=30,
|
|
69
|
-
)
|
|
70
|
-
# 测试连接
|
|
71
|
-
await self._redis.ping()
|
|
72
|
-
logger.info("✅ Redis 连接成功")
|
|
73
|
-
return self._redis
|
|
74
|
-
except Exception as e:
|
|
75
|
-
logger.warning(f"⚠️ Redis 连接失败 (尝试 {attempt + 1}/{max_retries}): {e}")
|
|
76
|
-
logger.warning(f"详细错误信息:\n{traceback.format_exc()}")
|
|
77
|
-
if attempt < max_retries - 1:
|
|
78
|
-
await asyncio.sleep(delay)
|
|
79
|
-
else:
|
|
80
|
-
raise ConnectionError(f"❌ 无法连接 Redis: {e}")
|
|
81
|
-
|
|
82
|
-
async def _ensure_connection(self):
|
|
83
|
-
"""确保连接有效"""
|
|
84
|
-
if self._redis is None:
|
|
85
|
-
await self.connect()
|
|
86
|
-
try:
|
|
87
|
-
await self._redis.ping()
|
|
88
|
-
except Exception as e:
|
|
89
|
-
logger.warning(f"🔄 Redis 连接失效,尝试重连...: {e}")
|
|
90
|
-
self._redis = None
|
|
91
|
-
await self.connect()
|
|
92
|
-
|
|
93
|
-
async def put(self, request: Request, priority: int = 0) -> bool:
|
|
94
|
-
"""放入请求到队列"""
|
|
95
|
-
await self._ensure_connection()
|
|
96
|
-
score = -priority
|
|
97
|
-
key = self._get_request_key(request)
|
|
98
|
-
try:
|
|
99
|
-
# 🔥 使用专用的序列化工具清理 Request
|
|
100
|
-
clean_request = self.request_serializer.prepare_for_serialization(request)
|
|
101
|
-
|
|
102
|
-
serialized = pickle.dumps(clean_request)
|
|
103
|
-
pipe = self._redis.pipeline()
|
|
104
|
-
pipe.zadd(self.queue_name, {key: score})
|
|
105
|
-
pipe.hset(f"{self.queue_name}:data", key, serialized)
|
|
106
|
-
result = await pipe.execute()
|
|
107
|
-
|
|
108
|
-
if result[0] > 0:
|
|
109
|
-
logger.debug(f"✅ 成功入队: {request.url}")
|
|
110
|
-
return result[0] > 0
|
|
111
|
-
except Exception as e:
|
|
112
|
-
logger.error(f"❌ 放入队列失败: {e}")
|
|
113
|
-
logger.error(f"详细错误信息:\n{traceback.format_exc()}")
|
|
114
|
-
return False
|
|
115
|
-
|
|
116
|
-
async def get(self, timeout: float = 5.0) -> Optional[Request]:
|
|
117
|
-
"""
|
|
118
|
-
获取请求(带超时)
|
|
119
|
-
:param timeout: 最大等待时间(秒),避免无限轮询
|
|
120
|
-
"""
|
|
121
|
-
await self._ensure_connection()
|
|
122
|
-
start_time = asyncio.get_event_loop().time()
|
|
123
|
-
|
|
124
|
-
while True:
|
|
125
|
-
try:
|
|
126
|
-
# 尝试获取任务
|
|
127
|
-
result = await self._redis.zpopmin(self.queue_name, count=1)
|
|
128
|
-
if result:
|
|
129
|
-
key, score = result[0]
|
|
130
|
-
serialized = await self._redis.hget(f"{self.queue_name}:data", key)
|
|
131
|
-
if not serialized:
|
|
132
|
-
continue
|
|
133
|
-
|
|
134
|
-
# 移动到 processing
|
|
135
|
-
processing_key = f"{key}:{int(time.time())}"
|
|
136
|
-
pipe = self._redis.pipeline()
|
|
137
|
-
pipe.zadd(self.processing_queue, {processing_key: time.time() + self.timeout})
|
|
138
|
-
pipe.hset(f"{self.processing_queue}:data", processing_key, serialized)
|
|
139
|
-
pipe.hdel(f"{self.queue_name}:data", key)
|
|
140
|
-
await pipe.execute()
|
|
141
|
-
|
|
142
|
-
return pickle.loads(serialized)
|
|
143
|
-
|
|
144
|
-
# 检查是否超时
|
|
145
|
-
if asyncio.get_event_loop().time() - start_time > timeout:
|
|
146
|
-
return None
|
|
147
|
-
|
|
148
|
-
# 短暂等待,避免空轮询
|
|
149
|
-
await asyncio.sleep(0.1)
|
|
150
|
-
|
|
151
|
-
except Exception as e:
|
|
152
|
-
logger.error(f"❌ 获取队列任务失败: {e}")
|
|
153
|
-
logger.error(f"详细错误信息:\n{traceback.format_exc()}")
|
|
154
|
-
return None
|
|
155
|
-
|
|
156
|
-
async def ack(self, request: Request):
|
|
157
|
-
"""确认任务完成"""
|
|
158
|
-
await self._ensure_connection()
|
|
159
|
-
key = self._get_request_key(request)
|
|
160
|
-
cursor = 0
|
|
161
|
-
while True:
|
|
162
|
-
cursor, keys = await self._redis.zscan(self.processing_queue, cursor, match=f"{key}:*")
|
|
163
|
-
if keys:
|
|
164
|
-
pipe = self._redis.pipeline()
|
|
165
|
-
for k in keys:
|
|
166
|
-
pipe.zrem(self.processing_queue, k)
|
|
167
|
-
pipe.hdel(f"{self.processing_queue}:data", k)
|
|
168
|
-
await pipe.execute()
|
|
169
|
-
if cursor == 0:
|
|
170
|
-
break
|
|
171
|
-
|
|
172
|
-
async def fail(self, request: Request, reason: str = ""):
|
|
173
|
-
"""标记任务失败"""
|
|
174
|
-
await self._ensure_connection()
|
|
175
|
-
key = self._get_request_key(request)
|
|
176
|
-
await self.ack(request)
|
|
177
|
-
|
|
178
|
-
retry_key = f"{self.failed_queue}:retries:{key}"
|
|
179
|
-
retries = await self._redis.incr(retry_key)
|
|
180
|
-
await self._redis.expire(retry_key, 86400)
|
|
181
|
-
|
|
182
|
-
if retries <= self.max_retries:
|
|
183
|
-
await self.put(request, priority=request.priority + 1)
|
|
184
|
-
logger.info(f"🔁 任务重试 [{retries}/{self.max_retries}]: {request.url}")
|
|
185
|
-
else:
|
|
186
|
-
failed_data = {
|
|
187
|
-
"url": request.url,
|
|
188
|
-
"reason": reason,
|
|
189
|
-
"retries": retries,
|
|
190
|
-
"failed_at": time.time(),
|
|
191
|
-
"request_pickle": pickle.dumps(request).hex(), # 可选:保存完整请求
|
|
192
|
-
}
|
|
193
|
-
await self._redis.lpush(self.failed_queue, pickle.dumps(failed_data))
|
|
194
|
-
logger.error(f"❌ 任务彻底失败 [{retries}次]: {request.url}")
|
|
195
|
-
|
|
196
|
-
def _get_request_key(self, request: Request) -> str:
|
|
197
|
-
"""生成请求唯一键"""
|
|
198
|
-
return f"url:{hash(request.url)}"
|
|
199
|
-
|
|
200
|
-
async def qsize(self) -> int:
|
|
201
|
-
"""获取队列大小"""
|
|
202
|
-
await self._ensure_connection()
|
|
203
|
-
return await self._redis.zcard(self.queue_name)
|
|
204
|
-
|
|
205
|
-
async def close(self):
|
|
206
|
-
"""关闭连接"""
|
|
207
|
-
if self._redis:
|
|
208
|
-
await self._redis.close()
|
|
1
|
+
import pickle
|
|
2
|
+
import time
|
|
3
|
+
import asyncio
|
|
4
|
+
from typing import Optional
|
|
5
|
+
import redis.asyncio as aioredis
|
|
6
|
+
import traceback
|
|
7
|
+
import os
|
|
8
|
+
|
|
9
|
+
from crawlo import Request
|
|
10
|
+
from crawlo.utils.log import get_logger
|
|
11
|
+
from crawlo.utils.request_serializer import RequestSerializer
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
logger = get_logger(__name__)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class RedisPriorityQueue:
|
|
18
|
+
"""
|
|
19
|
+
基于 Redis 的分布式异步优先级队列(生产级优化版)
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
def __init__(
|
|
23
|
+
self,
|
|
24
|
+
redis_url: str = None,
|
|
25
|
+
queue_name: str = "crawlo:requests",
|
|
26
|
+
processing_queue: str = "crawlo:processing",
|
|
27
|
+
failed_queue: str = "crawlo:failed",
|
|
28
|
+
max_retries: int = 3,
|
|
29
|
+
timeout: int = 300, # 任务处理超时时间(秒)
|
|
30
|
+
max_connections: int = 10, # 连接池大小
|
|
31
|
+
):
|
|
32
|
+
# 如果没有提供 redis_url,则从环境变量构造
|
|
33
|
+
if redis_url is None:
|
|
34
|
+
redis_host = os.getenv('REDIS_HOST', 'localhost')
|
|
35
|
+
redis_port = os.getenv('REDIS_PORT', '6379')
|
|
36
|
+
redis_db = os.getenv('REDIS_DB', '0')
|
|
37
|
+
redis_password = os.getenv('REDIS_PASSWORD', '')
|
|
38
|
+
|
|
39
|
+
if redis_password:
|
|
40
|
+
redis_url = f"redis://:{redis_password}@{redis_host}:{redis_port}/{redis_db}"
|
|
41
|
+
else:
|
|
42
|
+
redis_url = f"redis://{redis_host}:{redis_port}/{redis_db}"
|
|
43
|
+
|
|
44
|
+
self.redis_url = redis_url
|
|
45
|
+
self.queue_name = queue_name
|
|
46
|
+
self.processing_queue = processing_queue
|
|
47
|
+
self.failed_queue = failed_queue
|
|
48
|
+
self.max_retries = max_retries
|
|
49
|
+
self.timeout = timeout
|
|
50
|
+
self.max_connections = max_connections
|
|
51
|
+
self._redis = None
|
|
52
|
+
self._lock = asyncio.Lock() # 用于连接初始化的锁
|
|
53
|
+
self.request_serializer = RequestSerializer() # 处理序列化
|
|
54
|
+
|
|
55
|
+
async def connect(self, max_retries=3, delay=1):
|
|
56
|
+
"""异步连接 Redis,支持重试"""
|
|
57
|
+
async with self._lock:
|
|
58
|
+
if self._redis is not None:
|
|
59
|
+
return self._redis
|
|
60
|
+
|
|
61
|
+
for attempt in range(max_retries):
|
|
62
|
+
try:
|
|
63
|
+
self._redis = await aioredis.from_url(
|
|
64
|
+
self.redis_url,
|
|
65
|
+
decode_responses=False, # pickle 需要 bytes
|
|
66
|
+
max_connections=self.max_connections,
|
|
67
|
+
socket_connect_timeout=5,
|
|
68
|
+
socket_timeout=30,
|
|
69
|
+
)
|
|
70
|
+
# 测试连接
|
|
71
|
+
await self._redis.ping()
|
|
72
|
+
logger.info("✅ Redis 连接成功")
|
|
73
|
+
return self._redis
|
|
74
|
+
except Exception as e:
|
|
75
|
+
logger.warning(f"⚠️ Redis 连接失败 (尝试 {attempt + 1}/{max_retries}): {e}")
|
|
76
|
+
logger.warning(f"详细错误信息:\n{traceback.format_exc()}")
|
|
77
|
+
if attempt < max_retries - 1:
|
|
78
|
+
await asyncio.sleep(delay)
|
|
79
|
+
else:
|
|
80
|
+
raise ConnectionError(f"❌ 无法连接 Redis: {e}")
|
|
81
|
+
|
|
82
|
+
async def _ensure_connection(self):
|
|
83
|
+
"""确保连接有效"""
|
|
84
|
+
if self._redis is None:
|
|
85
|
+
await self.connect()
|
|
86
|
+
try:
|
|
87
|
+
await self._redis.ping()
|
|
88
|
+
except Exception as e:
|
|
89
|
+
logger.warning(f"🔄 Redis 连接失效,尝试重连...: {e}")
|
|
90
|
+
self._redis = None
|
|
91
|
+
await self.connect()
|
|
92
|
+
|
|
93
|
+
async def put(self, request: Request, priority: int = 0) -> bool:
|
|
94
|
+
"""放入请求到队列"""
|
|
95
|
+
await self._ensure_connection()
|
|
96
|
+
score = -priority
|
|
97
|
+
key = self._get_request_key(request)
|
|
98
|
+
try:
|
|
99
|
+
# 🔥 使用专用的序列化工具清理 Request
|
|
100
|
+
clean_request = self.request_serializer.prepare_for_serialization(request)
|
|
101
|
+
|
|
102
|
+
serialized = pickle.dumps(clean_request)
|
|
103
|
+
pipe = self._redis.pipeline()
|
|
104
|
+
pipe.zadd(self.queue_name, {key: score})
|
|
105
|
+
pipe.hset(f"{self.queue_name}:data", key, serialized)
|
|
106
|
+
result = await pipe.execute()
|
|
107
|
+
|
|
108
|
+
if result[0] > 0:
|
|
109
|
+
logger.debug(f"✅ 成功入队: {request.url}")
|
|
110
|
+
return result[0] > 0
|
|
111
|
+
except Exception as e:
|
|
112
|
+
logger.error(f"❌ 放入队列失败: {e}")
|
|
113
|
+
logger.error(f"详细错误信息:\n{traceback.format_exc()}")
|
|
114
|
+
return False
|
|
115
|
+
|
|
116
|
+
async def get(self, timeout: float = 5.0) -> Optional[Request]:
|
|
117
|
+
"""
|
|
118
|
+
获取请求(带超时)
|
|
119
|
+
:param timeout: 最大等待时间(秒),避免无限轮询
|
|
120
|
+
"""
|
|
121
|
+
await self._ensure_connection()
|
|
122
|
+
start_time = asyncio.get_event_loop().time()
|
|
123
|
+
|
|
124
|
+
while True:
|
|
125
|
+
try:
|
|
126
|
+
# 尝试获取任务
|
|
127
|
+
result = await self._redis.zpopmin(self.queue_name, count=1)
|
|
128
|
+
if result:
|
|
129
|
+
key, score = result[0]
|
|
130
|
+
serialized = await self._redis.hget(f"{self.queue_name}:data", key)
|
|
131
|
+
if not serialized:
|
|
132
|
+
continue
|
|
133
|
+
|
|
134
|
+
# 移动到 processing
|
|
135
|
+
processing_key = f"{key}:{int(time.time())}"
|
|
136
|
+
pipe = self._redis.pipeline()
|
|
137
|
+
pipe.zadd(self.processing_queue, {processing_key: time.time() + self.timeout})
|
|
138
|
+
pipe.hset(f"{self.processing_queue}:data", processing_key, serialized)
|
|
139
|
+
pipe.hdel(f"{self.queue_name}:data", key)
|
|
140
|
+
await pipe.execute()
|
|
141
|
+
|
|
142
|
+
return pickle.loads(serialized)
|
|
143
|
+
|
|
144
|
+
# 检查是否超时
|
|
145
|
+
if asyncio.get_event_loop().time() - start_time > timeout:
|
|
146
|
+
return None
|
|
147
|
+
|
|
148
|
+
# 短暂等待,避免空轮询
|
|
149
|
+
await asyncio.sleep(0.1)
|
|
150
|
+
|
|
151
|
+
except Exception as e:
|
|
152
|
+
logger.error(f"❌ 获取队列任务失败: {e}")
|
|
153
|
+
logger.error(f"详细错误信息:\n{traceback.format_exc()}")
|
|
154
|
+
return None
|
|
155
|
+
|
|
156
|
+
async def ack(self, request: Request):
|
|
157
|
+
"""确认任务完成"""
|
|
158
|
+
await self._ensure_connection()
|
|
159
|
+
key = self._get_request_key(request)
|
|
160
|
+
cursor = 0
|
|
161
|
+
while True:
|
|
162
|
+
cursor, keys = await self._redis.zscan(self.processing_queue, cursor, match=f"{key}:*")
|
|
163
|
+
if keys:
|
|
164
|
+
pipe = self._redis.pipeline()
|
|
165
|
+
for k in keys:
|
|
166
|
+
pipe.zrem(self.processing_queue, k)
|
|
167
|
+
pipe.hdel(f"{self.processing_queue}:data", k)
|
|
168
|
+
await pipe.execute()
|
|
169
|
+
if cursor == 0:
|
|
170
|
+
break
|
|
171
|
+
|
|
172
|
+
async def fail(self, request: Request, reason: str = ""):
|
|
173
|
+
"""标记任务失败"""
|
|
174
|
+
await self._ensure_connection()
|
|
175
|
+
key = self._get_request_key(request)
|
|
176
|
+
await self.ack(request)
|
|
177
|
+
|
|
178
|
+
retry_key = f"{self.failed_queue}:retries:{key}"
|
|
179
|
+
retries = await self._redis.incr(retry_key)
|
|
180
|
+
await self._redis.expire(retry_key, 86400)
|
|
181
|
+
|
|
182
|
+
if retries <= self.max_retries:
|
|
183
|
+
await self.put(request, priority=request.priority + 1)
|
|
184
|
+
logger.info(f"🔁 任务重试 [{retries}/{self.max_retries}]: {request.url}")
|
|
185
|
+
else:
|
|
186
|
+
failed_data = {
|
|
187
|
+
"url": request.url,
|
|
188
|
+
"reason": reason,
|
|
189
|
+
"retries": retries,
|
|
190
|
+
"failed_at": time.time(),
|
|
191
|
+
"request_pickle": pickle.dumps(request).hex(), # 可选:保存完整请求
|
|
192
|
+
}
|
|
193
|
+
await self._redis.lpush(self.failed_queue, pickle.dumps(failed_data))
|
|
194
|
+
logger.error(f"❌ 任务彻底失败 [{retries}次]: {request.url}")
|
|
195
|
+
|
|
196
|
+
def _get_request_key(self, request: Request) -> str:
|
|
197
|
+
"""生成请求唯一键"""
|
|
198
|
+
return f"url:{hash(request.url)}"
|
|
199
|
+
|
|
200
|
+
async def qsize(self) -> int:
|
|
201
|
+
"""获取队列大小"""
|
|
202
|
+
await self._ensure_connection()
|
|
203
|
+
return await self._redis.zcard(self.queue_name)
|
|
204
|
+
|
|
205
|
+
async def close(self):
|
|
206
|
+
"""关闭连接"""
|
|
207
|
+
if self._redis:
|
|
208
|
+
await self._redis.close()
|
|
209
209
|
self._redis = None
|
crawlo/settings/__init__.py
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
#!/usr/bin/python
|
|
2
|
-
# -*- coding:UTF-8 -*-
|
|
3
|
-
"""
|
|
4
|
-
# @Time : 2025-05-11 11:08
|
|
5
|
-
# @Author : oscar
|
|
6
|
-
# @Desc : None
|
|
7
|
-
"""
|
|
1
|
+
#!/usr/bin/python
|
|
2
|
+
# -*- coding:UTF-8 -*-
|
|
3
|
+
"""
|
|
4
|
+
# @Time : 2025-05-11 11:08
|
|
5
|
+
# @Author : oscar
|
|
6
|
+
# @Desc : None
|
|
7
|
+
"""
|