📬 概述
QStash 是可靠的消息队列服务:
- HTTP 推送:自动推送消息到你的 API
- 自动重试:失败自动重试
- 延迟投递:支持延迟、定时
- DLQ:死信队列支持
🚀 快速开始
安装 SDK
bash
npm install @upstash/qstash
发送消息
javascript
import { Client } from '@upstash/qstash'
const client = new Client({ token: 'QSTASH_TOKEN' })
// 发送 JSON 消息
await client.publishJSON({
url: 'https://your-api.com/webhook',
body: { hello: 'world' },
})
// 延迟投递(秒)
await client.publishJSON({
url: 'https://your-api.com/webhook',
body: { task: 'later' },
delay: 60, // 1分钟后
})
// 定时投递
await client.publishJSON({
url: 'https://your-api.com/webhook',
body: { task: 'scheduled' },
notBefore: Math.floor(Date.now() / 1000) + 3600,
})
接收消息
javascript (Next.js)
// app/api/webhook/route.ts
import { receiver } from '@upstash/qstash/nextjs'
export const POST = receiver(async (req) => {
const body = await req.json()
console.log('Received:', body)
// 处理消息...
return new Response('OK')
})
📚 使用场景
异步任务
javascript
// 发送邮件任务
await client.publishJSON({
url: 'https://api.example.com/send-email',
body: { to: 'user@example.com', subject: 'Hello' },
})
Webhook 回调
javascript
// 支付成功后通知
await client.publishJSON({
url: 'https://webhook.site/xxx',
body: { event: 'payment.success', orderId: '123' },
})
定时任务
javascript
// 每天执行
await client.schedules.create({
destination: 'https://api.example.com/cron',
cron: '0 0 * * *', // 每天 0:00
})
⚠️ vs Kafka
| 功能 | QStash | Kafka |
|---|---|---|
| 自动推送 | ✅ | 需自己拉取 |
| 重试 | ✅ 自动 | 需配置 |
| 延迟/定时 | ✅ | ❌ |
| 无限吞吐 | 有限额 | ✅ |
建议:Webhook、异步任务用 QStash;高吞吐事件流用 Kafka。