跳转到内容
搜索文档

通过 Worker 发布到 Queue

直接从 Worker 发布到 Queue。

最后更新 查看 MarkdownAgent 设置

以下示例展示如何从 Worker 向 Queue 发布消息。示例使用接收请求正文中 JSON 负载并按原样写入 Queue 的 Worker,但在实际应用程序中,您可能在排队消息之前有更多逻辑。

前提条件

按如下方式配置 Wrangler 文件:

{
	"$schema": "./node_modules/wrangler/config-schema.json",
	"name": "my-worker",
	"queues": {
		"producers": [
			{
				"queue": "my-queue",
				"binding": "YOUR_QUEUE"
			}
		]
	}
}
"$schema" = "./node_modules/wrangler/config-schema.json"
name = "my-worker"

[[queues.producers]]
queue = "my-queue"
binding = "YOUR_QUEUE"

1. 创建 Worker

以下 Worker 脚本:

  1. 验证请求正文是否为有效的 JSON。
  2. 将负载发布到队列。
interface Env {
	YOUR_QUEUE: Queue;
}

export default {
	async fetch(req, env, ctx): Promise<Response> {
		// Validate the payload is JSON
		// In a production application, we may more robustly validate the payload
		// against a schema using a library like 'zod'
		let messages;
		try {
			messages = await req.json();
		} catch {
			// Return a HTTP 400 (Bad Request) if the payload isn't JSON
			return Response.json({ error: "payload not valid JSON" }, { status: 400 });
		}

		// Publish to the Queue
		try {
			await env.YOUR_QUEUE.send(messages);
		} catch (e) {
			const message = e instanceof Error ? e.message : "Unknown error";
			console.error(`failed to send to the queue: ${message}`);
			// Return a HTTP 500 (Internal Error) if our publish operation fails
			return Response.json({ error: message }, { status: 500 });
		}

		// Return a HTTP 200 if the send succeeded!
		return Response.json({ success: true });
	},
} satisfies ExportedHandler<Env>;

要部署此 Worker:

npx wrangler deploy

2. 发送测试消息

要确认成功向队列写入消息,请在命令行使用 curl

# Make sure to replace the placeholder with your shared secret
curl -XPOST "https://YOUR_WORKER.YOUR_ACCOUNT.workers.dev" --data '{"messages": [{"msg":"hello world"}]}'
{"success":true}

这将发出 HTTP POST 请求,若成功,将返回 HTTP 200 及 success: true 响应正文。

  • 若收到 HTTP 400,表示您尝试向队列发送格式错误的 JSON。
  • 若收到 HTTP 500,表示消息未成功写入 Queue。

您可以使用 wrangler tail 调试 console.log 的输出。

这篇文档对您有帮助吗?