次の例では、Worker から Queue にメッセージを送信する方法を示します。この例の Worker は、リクエストボディの JSON ペイロードを受け取り、そのまま Queue に書き込みます。実際のアプリケーションでは、メッセージをキューに入れる前に、さらにロジックを入れることが多いです。
- Cloudflare ダッシュボード ↗ または wrangler CLI で 作成したキュー。
- Cloudflare ダッシュボードまたは Wrangler ファイルで 設定した プロデューサー バインディング。
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"次の Worker スクリプトは次を行います。
- リクエストボディが有効な JSON であることを検証します。
- ペイロードをキューに送信します。
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キューへの書き込みが成功したことを確認するには、コマンドラインで 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 を使えます。