分布式部署
从多个节点提供单个文档
当多个节点提供相同的文档时,渲染文档的节点不一定是响应浏览器页面请求的节点。本次发布将该工作拆分为两个明确的部分——写入端,将文档的制品发布到共享存储;以及读取端,从任意节点提供这些制品。
如果你的应用当前调用 UseDoconutWebFarm(...),本页即为你的替代方案。本次发布中不存在 UseDoconutWebFarm 或 WebFarmOptions。
你的拓扑结构不会改变。 将共享根指向你今天使用的相同 UNC 路径,所有节点将继续按现有方式工作。变化在于发布成为你主动调用的操作,而不再是渲染的副作用。
替代 Web-farm 中间件的方案
之前只有一个中间件完成所有工作:它从共享文件夹提供预渲染的图像,并在另一个节点仍在写入时轮询。这种等待是盲目的预算——“阻塞最多三分钟,期望页面出现”。
现在,同样的工作被拆分为两个可见且可推理的调用:
node A open request
-> PublishAsync(...) writes pages, document info,
search index and metadata
into RootPath/{token}/
-> returns the token
node B ?token=...&page=7
-> UseDoconutCloud<FileShareCloudHandler>
-> reads RootPath/{token}/ and serves the page两端共享的配置
发布器使用 FileShareConfig 进行写入,读取处理程序使用相同的对象进行提供。如果 RootPath 或 UsePerTokenSubfolders 在两者之间不一致,另一节点将返回 404。 在唯一位置构建配置并注册一次,使两端读取相同的对象:
var rootPath = builder.Configuration["Doconut:SharedRoot"]!; // 例如 \\fileserver\doconut
builder.Services.AddSingleton(SharedStore.Config(rootPath, asyncPublish: false));
internal static class SharedStore
{
public static FileShareConfig Config(string rootPath, bool asyncPublish) => new()
{
Location = CloudLocation.FileShare,
RootPath = rootPath,
UsePerTokenSubfolders = true,
ReadReadyPollMs = asyncPublish ? 250 : 0,
};
}在启用后台发布时传入 asyncPublish: true。
FileShareConfig 位于 Doconut.Clouds,与 AzureConfig、AmazonConfig、GoogleCloudConfig、DropBoxConfig、RedisConfig、CDNConfig 和 FTPConfig 一起。在之前的库中这些位于 Doconut.Configs.Cloud;类名未改变。
| 属性 | 用途 |
|---|---|
Location | 用于 UNC/本地共享的 CloudLocation.FileShare |
RootPath | 每个节点都能访问的共享文件夹 |
UsePerTokenSubfolders | 将每个文档的制品保存在其独立的 {token} 文件夹中(默认 true) |
ReadReadyPollMs | 读取端等待后台发布仍在写入的页面的时长;0(默认)检查一次。对同步发布的文档没有影响 |
写入端 — 发布文档
注入 DistributedDocumentPublisher 并进行发布,而不是打开本地会话。一次调用即可渲染并写入完整的制品集——页面、文档信息、搜索索引和元数据——并在完成后返回:
app.MapPost("/api/open", async (string fileName, FileShareConfig shareConfig,
DistributedDocumentPublisher publisher, CancellationToken ct) =>
{
var path = Path.Combine("files", Path.GetFileName(fileName));
var config = new PdfConfig { AllowSearch = true };
var documentOptions = new DocOptions { TimeOut = 60 };
var publishOptions = new DistributedDocumentPublishOptions { CleanUpStagingDirectory = true };
DistributedDocumentPublishResult result = await publisher.PublishAsync(
path, shareConfig, config, documentOptions, publishOptions, ct);
return Results.Text(result.Token);
});DistributedDocumentPublishResult 包含 Token、ArtifactPath、TotalPages 和 Format。该令牌会像普通查看器令牌一样发送到浏览器。在集群中,端点还会返回签名的访问票证——参见跨节点安全性。
此单一调用取代了之前的两步——将文档打开为本地会话,然后使用 ExportToPng(sharedPath) 将图像转存到共享中。ExportToPng 和 ExportToCloud 在此没有对应的实现。
读取端 — 从共享提供服务
在客户端已经调用的同一分支上挂载 FileShare 处理程序,放在票据检查之后:
var app = builder.Build();
app.UseDoconutResources();
app.MapWhen(
ctx => ctx.Request.Path.Value?.EndsWith("DocImage.axd", StringComparison.OrdinalIgnoreCase) == true,
branch =>
{
branch.UseDoconutDistributedDocumentSecurity(); // 已签名的票据 — 见下文
branch.UseDoconutCloud<FileShareCloudHandler>(options =>
{
options.Location = CloudLocation.FileShare;
options.CloudUploadConfig = app.Services.GetRequiredService<FileShareConfig>();
}, "/");
});UseDoconutCloud 在此版本中是通用的:提供者是类型参数,而不是在中间件内部切换的 Location 值。处理程序命名为 <Provider>CloudHandler — FileShareCloudHandler、AzureCloudHandler、AmazonS3CloudHandler、GoogleCloudHandler、DropBoxCloudHandler、RedisCloudHandler、FTPCloudHandler 和 CDNCloudHandler。使用路径前缀 "/" 时,处理程序会响应所有到达其分支的请求。
CDN 处理程序是 只读 — 它提供已经在 CDN 上的内容;不会进行上传。
可选:后台发布
默认情况下,PublishAsync 在返回之前会渲染完整文档。为了在令牌生成后立即返回,并让托管的工作者在同一文件夹中渲染,需注册可选队列,并使用 asyncPublish: true 构建共享配置:
builder.Services.AddDoconut(options => { /* … */ });
builder.Services.AddDoconutDistributedAsyncPublish();如果未进行此注册,则没有任何注册,发布保持同步,完全如之前一样。
然后调用 EnqueueAsync 而不是 PublishAsync。(DistributedDocumentPublishOptions.Async 仅是你的代码可以读取的标志,用于在两条路径之间选择;发布者会忽略它。)队列是有界的:当队列饱和时,EnqueueAsync 会抛出 DistributedPublishQueueFullException。使用 503 和 Retry-After 头部来响应,以便客户端退避而不是卡住:
app.MapPost("/api/open", async (string fileName, FileShareConfig shareConfig,
IDistributedPublishQueue publishQueue, HttpResponse response, CancellationToken ct) =>
{
var path = Path.Combine("files", Path.GetFileName(fileName));
var config = new PdfConfig { AllowSearch = true };
var documentOptions = new DocOptions { TimeOut = 60 };
var publishOptions = new DistributedDocumentPublishOptions { FirstPagePriority = true };
try
{
var token = await publishQueue.EnqueueAsync(
path, shareConfig, config, documentOptions, publishOptions, ct);
return Results.Text(token);
}
catch (DistributedPublishQueueFullException)
{
response.Headers["Retry-After"] = "5";
return Results.StatusCode(503);
}
});尚未写入的页面:HTTP 202
使用后台发布时,页面请求可能在工作者写入该页面之前到达。读取端会等待最多 ReadReadyPollMs,随后返回 HTTP 202 Accepted,而不是阻塞请求。
FirstPagePriority = true 缩短了首次查看的等待时间:页面 1 首先写入文档文件夹,因此文档在后续页面仍在渲染时即可打开。此行为仅适用于写入每个令牌文件夹的后台发布(UsePerTokenSubfolders = true);同步的 PublishAsync 会忽略它,因为其调用者始终等待完整文档。
这将等待转移到客户端,且是有界且可见的。请在小部件上启用重试:
const objViewer = $('#div_ctlDoc').docViewer({
BasePath: '/',
ResPath: 'doconut-res/images',
retryOn409: true // 重试 202(以及旧版 409)就绪响应
});未进行 重试 的客户端会在仍在渲染的页面上显示破损的瓦片。重试预算及其默认值(retryInitialDelayMs、retryBackoffFactor、retryMaxDelayMs、retryMaxAttempts、retryMaxTotalMs)在 查看器配置 中有文档说明。
这对 —— 使用 FirstPagePriority 的后台发布,加上读取端轮询 —— 替代了之前的 PageWaitTimeSeconds 和 StartWaitFromPage 设置。两者均已不再存在。
节点间的安全性
会话绑定的令牌假设提供服务的节点看到了打开请求。在集群中并非如此,因此每会话检查会拒绝合法请求;因此集群会设置 UnsafeMode = true。
UnsafeMode = true 不是安全模型——它是对已不再适用的模型的移除。 将其替换为签名访问票证,每个节点都可以独立验证。四个部分协同工作。
1. 在每个节点上注册票证安全。 票证使用 ASP.NET Core 数据保护进行保护,因此每个节点必须使用相同的密钥环和应用程序名称;使用不同密钥的节点无法读取另一个节点签发的票证。
using Microsoft.AspNetCore.DataProtection;
builder.Services.AddDataProtection()
.PersistKeysToFileSystem(new DirectoryInfo(@"\\fileserver\doconut-keys")) // 在每个节点上共享
.SetApplicationName("doconut-farm");
builder.Services.AddDoconut(options => options.UnsafeMode = true);
builder.Services.AddDoconutDistributedDocumentSecurity(options =>
{
options.TicketLifetimeMinutes = 60; // 默认
});2. 在读取端检查票证。 UseDoconutDistributedDocumentSecurity() 在读取分支中位于 UseDoconutCloud 之前,如 读取端示例 所示。
3. 在文档打开时签发票证。 票证标识令牌、浏览器(通过读取端比较的 cookie)以及已登录的用户(如果有):
using System.Security.Claims;
using Microsoft.Extensions.Options;
app.MapPost("/api/open", async (string fileName, HttpContext http, FileShareConfig shareConfig,
DistributedDocumentPublisher publisher, IDocumentAccessTicketProtector protector,
IOptions<DistributedDocumentSecurityOptions> security, CancellationToken ct) =>
{
var path = Path.Combine("files", Path.GetFileName(fileName));
var result = await publisher.PublishAsync(path, shareConfig, ct: ct);
// 通过读取端检查的 cookie 将票据绑定到此浏览器。
var cookieName = security.Value.BrowserCookieName; // "doconut-client" 默认
if (!http.Request.Cookies.TryGetValue(cookieName, out var browserId) || string.IsNullOrEmpty(browserId))
{
browserId = Guid.NewGuid().ToString("N");
http.Response.Cookies.Append(cookieName, browserId, new CookieOptions
{
HttpOnly = true,
Secure = http.Request.IsHttps,
SameSite = SameSiteMode.Lax
});
}
var access = protector.Protect(new DocumentAccessTicket
{
Token = result.Token,
BrowserId = browserId,
UserId = http.User.FindFirstValue(ClaimTypes.NameIdentifier) ?? "",
ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(security.Value.TicketLifetimeMinutes),
Nonce = Guid.NewGuid().ToString("N")
});
return Results.Json(new { token = result.Token, access });
});4. 将两者都传递给小部件。 查看器在每个请求中将票证作为 access 发送:
const resp = await fetch('/api/open?fileName=Sample.pdf', { method: 'POST' });
const { token, access } = await resp.json();
objViewer.View(token, access);读取端会拒绝票证缺失、无效、针对其他令牌签发、已过期、绑定到其他浏览器 cookie,或签发给其他已登录用户的请求。它返回 403 —— 对于页面和缩略图请求返回 UnauthorizedMessage 错误图片,其他情况下返回纯文本。请使用真实浏览器或保持 cookie 的客户端进行测试。
切勿将 UnsafeMode = true 带回单节点部署,也不要将其视为单节点上会话检查失败的快捷方式——在那种情况下正确的修复是 AddSession() / UseSession()。参见 会话与安全。
关闭已发布的文档
CloseDocument(token) 在注入的 Viewer 上会释放本地会话。要从共享中移除文档的已发布产物,发布者提供:
bool CloseDistributedDocument(FileShareConfig fileShareConfig, string token)使用与文档发布时相同的 FileShareConfig 进行传递。
设置逐项映射
| 之前 | 现在 |
|---|---|
UseDoconutWebFarm(new WebFarmOptions { … }) | PublishAsync(...) 在写入端使用,UseDoconutCloud<FileShareCloudHandler>(...) 在读取端使用 |
WebFarmOptions.Path | FileShareConfig.RootPath |
PageWaitTimeSeconds / StartWaitFromPage | 使用 DistributedDocumentPublishOptions.FirstPagePriority 的后台发布,加上 FileShareConfig.ReadReadyPollMs |
viewer.OpenDocument(...) then viewer.ExportToPng(share) | 一个 PublishAsync(...) 调用 |
viewer.ExportToCloud(cloudConfig) | PublishAsync(...) 使用提供者的配置 |
UseDoconutCloud(new CloudOptions { Location = … }) | UseDoconutCloud<THandler>(options => …, pathPrefix) |
DocOptions.IsWebfarm / WebfarmPath | 仍然存在,拼写为 IsWebFarm / WebFarmPath — 在发布路径上不需要 |
Doconut.Configs.Cloud | Doconut.Clouds |
检查清单
- 在一个帮助程序中构建
FileShareConfig,注册一次,并在两个部分中使用它。 - 将
RootPath指向您已经使用的共享。 - 使用
PublishAsync(...)进行发布;删除所有ExportToPng/ExportToCloud调用。 - 在客户端调用的分支上使用
UseDoconutCloud<FileShareCloudHandler>(...)提供服务。 - 使用后台发布时,同时打开
FirstPagePriority和retryOn409,并为读取端提供非零的ReadReadyPollMs。 - 用签名访问票据替代每会话检查——每个节点一个数据保护密钥环,读取分支上的
UseDoconutDistributedDocumentSecurity(),以及来自开放端点的票据——且不要单独部署UnsafeMode = true。 - 通过在一个节点打开文档并从另一个节点请求后续页面来验证。
此页面对您有帮助吗?