mcpField
E
encore-pubsub

encore-pubsub

github.com/encoredev开发30429 次安装2 天前更新
代码仓库

关于 encore-pubsub

encore-pubsub 是面向 Encore 服务的异步消息传递技能,介绍如何用 Topic 发布事件、用 Subscription 处理事件,以及消息投递保证和声明规范。

主要功能

  1. 01通过 Topic 发布事件
  2. 02通过 Subscription 处理事件
  3. 03用 Attribute 标记筛选或排序字段
  4. 04通过 Publisher 引用传递发布权限
  5. 05配置至少一次或恰好一次投递

适用场景

  1. 01服务间异步传递事件
  2. 02处理订单创建等领域事件
  3. 03按消息属性筛选或排序
  4. 04将耗时工作移出发布调用

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/encoredev/skills --skill encore-pubsub

安装后在 Claude Code 中输入/encore-pubsub确认已加载。

详细介绍

Encore Pub/Sub

说明

Pub/Sub 用于服务之间的异步消息传递。生产者向 Topic 发布事件;消费者附加 Subscription 以作出响应。资源必须在包级别声明——绝不能在函数内声明。

主题

import { Topic } from "encore.dev/pubsub";

interface OrderCreatedEvent {
  orderId: string;
  userId: string;
  total: number;
}

// Package level declaration
export const orderCreated = new Topic<OrderCreatedEvent>("order-created", {
  deliveryGuarantee: "at-least-once",
});
发布
await orderCreated.publish({
  orderId: "123",
  userId: "user-456",
  total: 99.99,
});
订阅
import { Subscription } from "encore.dev/pubsub";

const _ = new Subscription(orderCreated, "send-confirmation-email", {
  handler: async (event) => {
    await sendEmail(event.userId, event.orderId);
  },
});
消息属性

对于应视为消息属性的字段(用于筛选/排序),请使用 Attribute<T>:

import { Topic, Attribute } from "encore.dev/pubsub";

interface CartEvent {
  cartId: Attribute<string>;  // Used for ordering
  userId: string;
  action: "add" | "remove";
  productId: string;
}

// Ordered topic: events with same cartId delivered in order
export const cartEvents = new Topic<CartEvent>("cart-events", {
  deliveryGuarantee: "at-least-once",
  orderingAttribute: "cartId",
});
主题引用

在向其他代码传递主题访问权限的同时,保持静态分析:

import { Publisher } from "encore.dev/pubsub";

const publisherRef = orderCreated.ref<Publisher>();

async function notifyOrder(ref: typeof publisherRef, orderId: string) {
  await ref.publish({ orderId, userId: "123", total: 99.99 });
}

投递保证

  • at-least-once(默认):可能会重复投递 → 处理程序必须具备幂等性。
  • exactly-once:限制更严格,吞吐量有上限(AWS 每个主题 300 msg/s,GCP 每个区域 3000+ msg/s)。发布端不会进行去重。

指南

  • 主题和订阅必须在包级别声明。
  • 订阅处理程序必须具备幂等性(默认采用至少一次投递)。
  • 对于用于筛选/排序的字段,请使用 Attribute<T>,不要将其用于任意元数据。
  • 不要在 publish 调用方中执行繁重的同步工作——publish 会在消息入队后返回。

评论

支持 Markdown