0Pricing
Edge Computing with Cloudflare Workers & Deno · 课时

队列与异步任务

利用 Cloudflare Queues 管理异步任务,并在大规模场景下执行后台处理

队列与异步任务 是 CoddyKit 上的免费 Edge Computing with Cloudflare Workers & Deno 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Edge Computing with Cloudflare Workers & Deno 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Edge Computing with Cloudflare Workers & Deno 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Async Tasks at the Edge

At the edge, users expect lightning-fast responses. But not every task needs to happen instantly. Sometimes, you have operations that can run in the background, like sending emails, processing analytics, or generating reports.

These are called asynchronous tasks. They don't block the user's immediate request, allowing your Worker to respond quickly while the longer task completes separately.

Introducing Cloudflare Queues

Cloudflare Queues provide a robust way to manage these asynchronous tasks. They act as a buffer, allowing different parts of your application (often Cloudflare Workers) to communicate without needing to be directly available at the same time.

Think of it like a to-do list where one Worker adds tasks, and another Worker picks them up when it's ready.

Queue Fundamentals: P-C-M

Every message queue system, including Cloudflare Queues, revolves around three core concepts:

  • Producers: The entities that create and send messages to the queue. In our case, this will often be a Cloudflare Worker responding to an HTTP request.
  • Consumers: The entities that retrieve messages from the queue and process them. This is typically another Cloudflare Worker configured to listen to the queue.
  • Messages: The actual data or task instructions being passed through the queue.

Configuring Your First Queue

To use Cloudflare Queues, you first need to create a queue in your Cloudflare dashboard or via the Wrangler CLI. Once created, you bind it to a Worker, making it accessible through the Worker's env object.

This binding specifies the name your Worker will use to interact with the queue (e.g., env.MY_QUEUE).

Sending Messages to a Queue

A Worker acting as a Producer will send messages to a bound queue using the send() method. This method takes a JavaScript object as its argument, which will be serialized and stored in the queue.

The send() operation is asynchronous itself, but it ensures the message is enqueued quickly, allowing the producer Worker to complete its primary task without waiting for the message to be processed.

Worker Producing Messages

Here's an example of a Worker receiving an HTTP request and sending a simple message to a queue named MY_QUEUE. The user gets an immediate response.

export interface Env {
  MY_QUEUE: Queue;
}

export default {
  async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
    const url = new URL(request.url);
    if (url.pathname === '/send-task') {
      const message = {
        type: 'email_notification',
        userId: 'user123',
        subject: 'Welcome to CoddyKit!'
      };
      await env.MY_QUEUE.send(message);
      return new Response('Email task enqueued!', { status: 200 });
    }
    return new Response('Hello from Producer Worker!', { status: 200 });
  },
};

Processing Queue Messages

A Worker acting as a Consumer is configured with a special queue handler. This handler is invoked by Cloudflare when there are messages available in the bound queue. Messages are delivered in batches for efficiency.

Inside the queue handler, you iterate through the batch.messages array. For each message, you can access its body (the data sent by the producer) and perform the necessary background processing.

Worker Consuming Messages

This Worker is configured to listen to MY_QUEUE. It processes each message in the batch. If a message is processed successfully, message.ack() acknowledges it. If an error occurs, message.retry() sends it back to the queue for another attempt.

export interface Env {
  MY_QUEUE: Queue;
}

export default {
  async queue(batch: MessageBatch, env: Env): Promise<void> {
    for (const message of batch.messages) {
      try {
        const data = message.body as {
          type: string;
          userId: string;
          subject: string;
        };
        console.log(`Processing ${data.type} for ${data.userId}: ${data.subject}`);
        // Simulate sending an email or other background task
        await new Promise(resolve => setTimeout(resolve, 500));
        message.ack(); // Mark message as processed successfully
      } catch (error) {
        console.error(`Error processing message: ${error}`);
        message.retry(); // Re-queue for another attempt
      }
    }
  },
};

Why Use Edge Queues?

Cloudflare Queues offer several powerful benefits for edge applications:

  • Decoupling: Producers and consumers don't need to know about each other directly.
  • Reliability: Messages are persistent and can be retried automatically if processing fails.
  • Load Leveling: Queues absorb spikes in demand, preventing your backend services from being overwhelmed.
  • Scalability: Easily scale processing by adding more consumer Workers without affecting producers.
  • Asynchronous Processing: Crucial for keeping user-facing responses fast.

Practical Queue Use Cases

Queues are incredibly versatile. Here are some common scenarios where Cloudflare Queues shine:

  • Analytics & Logging: Collect and process user event data in the background.
  • Image/Video Processing: Trigger resizing or watermarking after an upload.
  • Notifications: Send emails, SMS, or push notifications without delaying the user.
  • Data Synchronization: Propagate changes to multiple downstream services asynchronously.
  • Batch Jobs: Schedule and execute periodic data transformations or cleanup tasks.

Queue Concepts Check

Consider a scenario where a Cloudflare Worker needs to initiate a background task (e.g., sending an email) without delaying the user's response. Which of the following statements about Cloudflare Queues are correct for this scenario?

Recap & Next Steps

You've now explored Cloudflare Queues, a powerful tool for managing asynchronous tasks at the edge. We covered the producer-consumer model, how to send and process messages, and the significant benefits queues bring, such as improved reliability, scalability, and faster user responses.

By decoupling tasks with queues, your edge applications can handle complex operations efficiently without compromising performance. Experiment with creating your own queues and Workers to build robust, asynchronous workflows!

常见问题解答

「队列与异步任务」课时是免费的吗?

是的 — 「队列与异步任务」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Edge Computing with Cloudflare Workers & Deno 课程的其余内容,请升级到 CoddyKit PRO。 Edge Computing with Cloudflare Workers & Deno 课程共包含 4 节课。

「队列与异步任务」这节课中我会学到什么?

利用 Cloudflare Queues 管理异步任务,并在大规模场景下执行后台处理 你通过在浏览器中直接运行的动手代码来练习 Edge Computing with Cloudflare Workers & Deno,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Edge Computing with Cloudflare Workers & Deno 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Edge Computing with Cloudflare Workers & Deno 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「队列与异步任务」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Edge Computing with Cloudflare Workers & Deno 课中编写并运行代码吗?

能。每节 Edge Computing with Cloudflare Workers & Deno 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. WebSockets 与实时通信
  2. 队列与异步任务
  3. 服务绑定与集成
  4. Cron 触发器与定时 Workers
← 返回 Edge Computing with Cloudflare Workers & Deno