配置选项
全局配置
通过 Pa.Configure() 进行全局配置:
Pa.Configure(c =>
{
c.Options.DefaultCacheDuration = TimeSpan.FromMinutes(5);
c.Options.DefaultTimeout = TimeSpan.FromSeconds(30);
c.Options.RetryCount = 3;
c.Options.EnableMetrics = true;
c.Options.EnableTracing = true;
c.UseRecipesFolder("./recipes");
});
选项一览
基础选项
| 选项 | 默认值 | 说明 |
|---|---|---|
DefaultCacheDuration | 5 分钟 | 缓存有效期 |
DefaultTimeout | 30 秒 | HTTP 超时 |
RetryCount | 3 | 重试次数 |
EnableMetrics | true | 是否启用指标 |
EnableTracing | true | 是否启用追踪 |
EnableRateLimit | false | 是否启用限流 |
限流选项
Pa.Configure(c => c.Options.RateLimit = new RateLimitOptions
{
PermitLimit = 10,
Window = TimeSpan.FromSeconds(1)
});
| 选项 | 默认值 | 说明 |
|---|---|---|
PermitLimit | 10 | 窗口内最大请求数 |
Window | 1 秒 | 时间窗口 |
熔断选项
Pa.Configure(c => c.Options.CircuitBreaker = new CircuitBreakerOptions
{
FailureThreshold = 5,
DurationOfBreak = TimeSpan.FromSeconds(60)
});
| 选项 | 默认值 | 说明 |
|---|---|---|
FailureThreshold | 5 | 连续失败次数阈值 |
DurationOfBreak | 60 秒 | 熔断持续时间 |
代理池配置
Pa.Configure(c => c
.UseProxyPool(new[]
{
"http://127.0.0.1:7890",
"http://127.0.0.1:7891",
})
.ProxyStrategy(ProxyStrategy.RoundRobin));
| 策略 | 说明 |
|---|---|
ProxyStrategy.RoundRobin | 轮询 |
ProxyStrategy.Random | 随机 |
代理池自带健康跟踪,连续失败的代理会自动禁用。
加载外部 Recipe
// 从文件夹加载
Pa.Configure(c => c.UseRecipesFolder("./recipes"));
// 从单个文件加载
Pa.Configure(c => c.UseRecipeFile("./recipes/myapi.yaml"));
中间件注册
Pa.Configure(c =>
{
c.UseMiddleware(new MyAuthMiddleware());
c.UseMiddleware(new LoggingMiddleware());
});
中间件按 Order 属性排序执行。
依赖注入集成
在 ASP.NET Core 中通过 DI 配置:
builder.Services.AddPa(opt =>
{
opt.DefaultCacheDuration = TimeSpan.FromMinutes(10);
opt.RecipesFolder = "./recipes";
opt.EnableMetrics = true;
});
// 注册自定义中间件
builder.Services.AddSingleton<IScrapeMiddleware, MyAuthMiddleware>();
插件化
第三方包通过 [assembly: PaScraperModule] 自动发现:
// 在第三方程序集中
[assembly: PaScraperModule]
public class MyModule : IPaModule
{
public void Register(IPaConfigurator config)
{
config.Define("MySource", b => b
.Get("https://example.com")
.ParseHtml(p => p
.Container(".item")
.Field("title", f => f.Selector("h3"))));
}
}
引用该包后,Pa.DiscoverFromLoadedAssemblies() 会自动发现并加载。