Skip to content

非公式本サイトは非公式の日本語ドキュメントであり、Cloudflare 公式サイトではありません。最新情報はdevelopers.cloudflare.comをご確認ください。

Workers から Queue に送信する

Worker から直接 Queue にメッセージを送信します。

最終更新 Markdown で表示Agent セットアップ

次の例では、Worker から Queue にメッセージを送信する方法を示します。この例の Worker は、リクエストボディの JSON ペイロードを受け取り、そのまま Queue に書き込みます。実際のアプリケーションでは、メッセージをキューに入れる前に、さらにロジックを入れることが多いです。

前提条件

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 への書き込みに失敗したためです。

console.log の出力をデバッグするには wrangler tail を使えます。

役に立ちましたか?