将 Webhook 处理卸载到队列
在 Web 应用程序中,通常希望将异步任务的处理卸载到队列中,对于这些任务,客户端不需要立即响应。这样做可以使您的 Web 应用程序保持快速响应,而不是占用宝贵的资源等待长时间运行的进程完成。
您可能想要部署此技术的其中一个实例是在处理 Webhook时。在从不需要响应的非人类客户端接收 Webhook 请求后,您可以立即将该工作卸载到队列中,以便更有效地处理它。
在本教程中,我们将向您展示如何在处理 GitHub 仓库的 Webhook 请求时执行此技术。
在游乐场中尝试
✏️ 查看此游乐场,它实现了 GitHub 仓库 webhook 处理程序.
使用 Deno Deploy 游乐场,您可以立即部署自己的 GitHub webhook 处理程序,该处理程序同时使用队列和 Deno KV。我们将在稍后逐步介绍此代码的功能。
为仓库配置 GitHub webhook
要尝试您在游乐场中启动的 webhook,请为您的 GitHub 仓库设置新的 webhook 配置。您可以在仓库的“设置”中找到 webhook 配置。
代码演练
我们的 webhook 处理程序函数相对简单 - 不带注释,总共只有 23 行代码。它连接到 Deno KV 数据库,设置队列监听器以处理传入消息,并使用 Deno.serve
设置一个简单的服务器,该服务器响应传入的 webhook 请求。
阅读下面的注释,了解每个步骤发生了什么。
server.ts
// Get a handle for a Deno KV database instance. KV is built in to the Deno
// runtime, and is available with zero config both locally and on Deno Deploy
const kv = await Deno.openKv();
// Set up a listener that will handle work that is offloaded from our server.
// In this case, it's just going to add incoming webhook payloads to a KV
// database, with a timestamp.
kv.listenQueue(async (message) => {
await kv.set(["github", Date.now()], message);
});
// This is a simple HTTP server that will handle incoming POST requests from
// GitHub webhooks.
Deno.serve(async (req: Request) => {
if (req.method === "POST") {
// GitHub sends webhook requests as POST requests to your server. You can
// configure GitHub to send JSON in the POST body, which you can then parse
// from the request object.
const payload = await req.json();
await kv.enqueue(payload);
return new Response("", { status: 200 });
} else {
// If the server is handling a GET request, this will just list out all the
// webhook events that have been recorded in our KV database.
const iter = kv.list<string>({ prefix: ["github"] });
const github = [];
for await (const res of iter) {
github.push({
timestamp: res.key[1],
payload: res.value,
});
}
return new Response(JSON.stringify(github, null, 2));
}
});