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

事件驱动架构

使用 Workers 和 Deno 构建事件驱动系统,响应实时数据和用户操作

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

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

What is Event-Driven Architecture?

Welcome! Today we'll explore Event-Driven Architecture (EDA). It's a design pattern where services communicate by producing and consuming events, rather than direct calls.

Think of it like a news channel: producers (reporters) publish news (events), and consumers (viewers) react to the news they're interested in.

  • Event: A significant change in state, like 'user registered'.
  • Producer: The system that generates and sends an event.
  • Consumer: The system that listens for and reacts to an event.

Why Event-Driven at the Edge?

EDA shines brightly at the edge, offering significant benefits for performance and scalability:

  • Decoupling: Services operate independently, reducing dependencies.
  • Scalability: Individual components can scale up or down based on event load.
  • Real-time Responsiveness: React to user actions or data changes instantly.
  • Resilience: If one consumer fails, others can still process events.

This makes your edge applications more robust and flexible.

Cloudflare Workers as Event Reactors

Cloudflare Workers are perfect for event-driven systems because they are inherently reactive. They spring into action when triggered by an event!

Common events that trigger Workers include:

  • Incoming HTTP requests (e.g., an API call)
  • Messages from a queue (e.g., Cloudflare Queues)
  • Scheduled cron jobs
  • Other Cloudflare service bindings

They act as lightweight, distributed consumers.

Code: Worker Reacting to HTTP Event

Here's a basic Worker that processes an incoming HTTP request as an 'event'. It reads a custom header to identify the event type and logs it.

Try changing the X-Event-Type header when you test it!

export default {
  async fetch(request, env, ctx) {
    const eventType = request.headers.get('X-Event-Type') || 'unknown_event';
    const eventData = await request.json().catch(() => ({}));

    console.log(`Worker received event: ${eventType}`);
    console.log(`Event data: ${JSON.stringify(eventData)}`);

    // In a real app, you'd process eventData here
    return new Response(`Event '${eventType}' processed!`, { status: 200 });
  },
};

Deno as an Event Originator

Just as Workers consume events, Deno applications can act as event producers. A Deno backend service or a CLI tool might generate events.

For instance, a Deno script could:

  • Detect a file change and send an event.
  • Process data and publish a 'data_processed' event.
  • Handle a user action and send a 'user_activity' event to your edge Worker.

Code: Deno Sends Event to Worker

This Deno script acts as a producer, sending a 'user_registered' event to our Cloudflare Worker via an HTTP POST request. The Worker then acts as the consumer.

Remember to replace 'YOUR_WORKER_URL' with your deployed Worker's URL!

// main.ts
async function sendUserRegisteredEvent() {
  const workerUrl = "https://your-worker-name.your-account.workers.dev"; // Replace this!

  const response = await fetch(workerUrl, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "X-Event-Type": "user_registered"
    },
    body: JSON.stringify({ userId: "user_abc", timestamp: Date.now() })
  });

  if (response.ok) {
    console.log("User registered event sent successfully!");
  } else {
    console.error("Failed to send event:", response.status, await response.text());
  }
}

sendUserRegisteredEvent();

Cloudflare Queues for Robust Events

For truly robust event-driven systems, especially at the edge, Cloudflare Queues are invaluable. They act as an event bus, providing a reliable buffer between producers and consumers.

  • Asynchronous: Producers don't wait for consumers to finish.
  • Guaranteed Delivery: Messages are durably stored until processed.
  • Load Leveling: Handles bursts of events without overwhelming consumers.
  • Decoupling: Producers and consumers don't need to know about each other directly.

Code: Worker Publishes to a Queue

Here, a Worker receives an HTTP request (an event) and then publishes a message to a Cloudflare Queue. This offloads heavy processing to a separate consumer.

To make this runnable, you'd need to bind a Queue in your wrangler.toml file (e.g., [[queues.producers]] binding = "MY_QUEUE" queue_name = "my-event-queue").

export default {
  async fetch(request, env, ctx) {
    const eventData = await request.json().catch(() => ({}));
    const eventType = eventData.type || 'api_trigger_event';

    // Publish event to a Cloudflare Queue
    // 'env.MY_QUEUE' refers to the queue binding configured
    await env.MY_QUEUE.send({
      eventType: eventType,
      payload: eventData
    });

    return new Response(`Event '${eventType}' queued successfully!`, { status: 202 });
  },
};

Code: Worker Consuming Queue Messages

This Worker is configured to consume messages directly from a Cloudflare Queue. It processes each message in a batch, extracting the event type and payload.

This Worker would have a queue handler instead of (or in addition to) a fetch handler. You'd configure this in your wrangler.toml (e.g., [[queues.consumers]] queue = "my-event-queue").

export default {
  async queue(batch, env, ctx) {
    for (const message of batch.messages) {
      const { eventType, payload } = message.body;
      console.log(`Processing event from queue: ${eventType}`);
      console.log(`Payload: ${JSON.stringify(payload)}`);

      // Implement your actual event processing logic here
      // e.g., update a database, send a notification, call another API
    }
  },
};

Quick Check: Event-Driven Concepts

Which of the following are key benefits of using an Event-Driven Architecture at the edge?

Recap: Event-Driven Edge Apps

Great job! You've learned about Event-Driven Architectures and how they supercharge applications at the edge.

  • EDA uses events, producers, and consumers for decoupled communication.
  • Cloudflare Workers are ideal for consuming and producing edge events.
  • Deno applications can act as powerful event producers.
  • Cloudflare Queues provide robust, asynchronous event delivery for resilience and scale.

This pattern is key for building highly responsive, scalable, and fault-tolerant edge applications. Keep exploring how events can transform your architecture!

常见问题解答

「事件驱动架构」课时是免费的吗?

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

「事件驱动架构」这节课中我会学到什么?

使用 Workers 和 Deno 构建事件驱动系统,响应实时数据和用户操作 你通过在浏览器中直接运行的动手代码来练习 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. 边缘微服务
  2. 事件驱动架构
  3. 地理定位与本地化
  4. Durable Objects 与有状态协调
← 返回 Edge Computing with Cloudflare Workers & Deno