我正在尝试按照 Web dev cody 视频在我自己的 NextJS API 上的 GET 路由上设置 upstash 速率限制器:https://www.youtube.com/watch?v=9xqlkAPnoTY(这基本上是演示Upstash 速率限制器存储库上的代码)。
这是我的代码,没有限制器,大约需要 50 毫秒才能完成:
import Albums from "@models/albums";
import { connectToDB } from "@utils/database";
import { NextResponse } from 'next/server'
export const GET = async () => {
try {
await connectToDB()
const albums = await Albums.find({})
return NextResponse.json(
albums,
{ status: 200 }
)
} catch (error) {
console.log(error)
return NextResponse.json(
"Failed to fetch all ablums",
{ status: 500 }
)
}
}
这是添加了 upstash 速率限制器的代码,大约需要 5 秒才能完成:
import Albums from "@models/albums";
import { connectToDB } from "@utils/database";
import { Ratelimit } from "@upstash/ratelimit";
import { Redis } from "@upstash/redis";
import { NextResponse } from 'next/server'
const ratelimit = new Ratelimit({
redis: Redis.fromEnv(),
limiter: Ratelimit.slidingWindow(1, "10 s")
})
export const GET = async (request) => {
try {
const ip = request.headers.get("x-forwarded-for") ?? "";
const { success, reset } = await ratelimit.limit(ip);
if (!success) {
const now = Date.now();
const retryAfter = Math.floor((reset - now) / 1000);
return new NextResponse("Too Many Requests", {
status: 429,
headers: {
["retry-after"]: `${retryAfter}`,
},
});
}
await connectToDB()
const albums = await Albums.find({})
return NextResponse.json(
albums,
{ status: 200 }
)
} catch (error) {
console.log(error)
return NextResponse.json(
"Failed to fetch all ablums",
{ status: 500 }
)
}
}
有人知道为什么在设置速率限制器的情况下突然需要这么长时间才能完成 API 调用吗?
这发生在我身上,因为我在环境变量中缺少
https://
中的 REDIS_URL
。
来自 upstash 的速率限制器似乎在 5 秒后返回
success: true
,因为它无法到达我的 redis 数据库。