Skip to content
Server Plugin

速率限制

所需依赖项: io.ktor:ktor-server-rate-limit

代码示例: rate-limit

Native 服务器Ktor 支持 Kotlin/Native,并允许您在无需额外运行时或虚拟机的情况下运行服务器。支持: ✅

RateLimit 插件允许您限制客户端在指定时间段内可以发出的请求数量。

Ktor 提供了几种配置速率限制的方式:

添加依赖项 ​

要使用 RateLimit,请将 ktor-server-rate-limit 工件添加到您的构建脚本中:

kotlin
implementation(ktorLibs.server.rateLimit)
上述代码段使用 Ktor 版本目录来指定 Ktor 依赖项。
groovy
implementation ktorLibs.server.rateLimit
上述代码段使用 Ktor 版本目录来指定 Ktor 依赖项。
xml
<dependency>
    <groupId>io.ktor</groupId>
    <artifactId>ktor-server-rate-limit-jvm</artifactId>
    <version>${ktor_version}</version>
</dependency>

安装 RateLimit ​

要将 RateLimit 插件安装到您的应用程序中,请将其传递给指定 模块模块允许您通过对路由进行分组来构建应用程序结构。 中的 install 函数。 以下示例展示了如何安装 RateLimit:

  • 在 embeddedServer() 函数调用中。
  • 在 Application 类上显式定义的 module() 扩展函数中。
kotlin
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import io.ktor.server.application.*
import io.ktor.server.plugins.ratelimit.*

fun main() {
    embeddedServer(Netty, port = 8080) {
        install(RateLimit)
        // ...
    }.start(wait = true)
}
kotlin
import io.ktor.server.application.*
import io.ktor.server.plugins.ratelimit.*
// ...
fun Application.module() {
    install(RateLimit)
    // ...
}

配置 RateLimit ​

概述 ​

Ktor 使用_令牌桶_(token bucket)算法进行速率限制,其工作原理如下:

  1. 创建一个具有指定容量的桶,该容量定义了可用令牌的数量。
  2. 每个传入的请求都会从桶中消耗一个令牌:
    • 如果容量充足,服务器将处理该请求,并在响应中包含以下标头:
      • X-RateLimit-Limit:桶的容量。
      • X-RateLimit-Remaining:桶中剩余的令牌数。
      • X-RateLimit-Reset:UTC 时间戳(以秒为单位),指定桶重新注满的时间。
    • 如果容量不足,服务器将通过 429 Too Many Requests 响应拒绝该请求。响应中包含 Retry-After 标头,指示客户端在发送另一个请求之前应等待多少秒。
  3. 经过指定的补充周期后,桶将被重新填满。

注册速率限制器 ​

您可以在全局范围内对整个应用程序应用速率限制,也可以为特定路由注册速率限制器:

  • 要全局应用速率限制,请调用 global() 函数并配置速率限制器:

    kotlin
    install(RateLimit) {
        global {
            rateLimiter(limit = 5, refillPeriod = 60.seconds)
        }
    }
  • 要为特定路由配置速率限制,请使用 register() 函数注册速率限制器:

    kotlin
    install(RateLimit) {
        register {
            rateLimiter(limit = 5, refillPeriod = 60.seconds)
        }
    }

以上示例展示了 RateLimit 插件所需的最简配置。 如果您使用 register(),还需要将注册的速率限制器应用到特定路由。

配置速率限制 ​

您可以使用以下选项配置速率限制器。

命名速率限制器 ​

使用 register() 函数为速率限制器分配名称。随后您可以将该命名速率限制器应用到特定路由:

kotlin
    install(RateLimit) {
        register(RateLimitName("protected")) {
            // ...
        }
    }

设置限制和补充周期 ​

使用 rateLimiter() 函数配置桶容量和补充周期:

  • limit 指定可用令牌的数量。
  • refillPeriod 指定桶被重新注满的频率。

以下示例允许每分钟最多 30 个请求:

kotlin
register(RateLimitName("protected")) {
    rateLimiter(limit = 30, refillPeriod = 60.seconds)
}

按键区分请求 ​

使用 requestKey() 函数为每个请求返回一个键。具有不同键的请求拥有独立的速率限制。默认情况下,所有请求共享同一个桶。

请确保请求键具有适当的 equals 和 hashCode 实现。

查询参数 ​

以下示例使用 login 查询参数来区分用户:

kotlin
register(RateLimitName("protected")) {
    requestKey { applicationCall ->
        applicationCall.request.queryParameters["login"]!!
    }
}
客户端 IP 地址 ​

要对每个客户端 IP 地址应用单独的速率限制,请使用 call.request.origin.remoteHost 作为请求键:

kotlin
register(RateLimitName("per-ip")) {
    rateLimiter(limit = 5, refillPeriod = 60.seconds)
    requestKey { call ->
        call.request.origin.remoteHost
    }
}

如果应用程序运行在代理或负载均衡器后面,请配置 Forwarded headers 插件,以便 origin.remoteHost 表示原始客户端地址而非代理地址。

API 密钥标头 ​

要按标头中发送的 API 密钥对请求进行速率限制,请从 requestKey() 返回该标头值:

kotlin
register(RateLimitName("per-api-key")) {
    rateLimiter(limit = 5, refillPeriod = 60.seconds)
    requestKey { call ->
        call.request.headers["X-Api-Key"] ?: "anonymous"
    }
}

您还可以将此方法与 API 密钥身份验证相结合,使用经过身份验证的主体(principal)作为请求键,而不是原始标头值。

访问令牌或 Bearer 令牌 ​

要对每个 Bearer 令牌应用单独的速率限制,请从 Authorization 标头返回原始令牌作为请求键:

kotlin
requestKey { call ->
    call.request.authorization()?.removePrefix("Bearer ") ?: "anonymous"
}

当请求经过身份验证时,建议使用身份验证主体作为请求键,以对每个经过身份验证的标识应用单独的速率限制。

对已验证用户进行速率限制 ​

您可以使用身份验证主体作为请求键,以按已验证用户应用速率限制。

将 rateLimit() 嵌套在 authenticate() 中,然后从 requestKey() 访问主体:

kotlin
install(Authentication) {
    basic("auth") { validate { UserIdPrincipal(it.name) } }
}
install(RateLimit) {
    register(RateLimitName("per-user")) {
        rateLimiter(limit = 10, refillPeriod = 60.seconds)
        requestKey { call.principal<UserIdPrincipal>()?.name ?: "anonymous" }
    }
}

routing {
    authenticate("auth") {
        rateLimit(RateLimitName("per-user")) {
            get("/api") { call.respondText("OK") }
        }
    }
}

设置请求权重 ​

使用 requestWeight() 函数指定每个请求消耗的令牌数量。该函数接收应用程序调用和请求键作为参数。

在以下示例中,带有 jetbrains 键的请求消耗一个令牌,而所有其他请求消耗两个令牌:

kotlin
register(RateLimitName("protected")) {
    requestKey { applicationCall ->
        applicationCall.request.queryParameters["login"]!!
    }
    requestWeight { applicationCall, key ->
        when (key) {
            "jetbrains" -> 1
            else -> 2
        }
    }
}

自定义响应 ​

使用 modifyResponse() 函数在应用速率限制时自定义响应。

例如,您可以添加自定义速率限制标头:

kotlin
register(RateLimitName("protected")) {
    modifyResponse { applicationCall, state ->
        applicationCall.response.header("X-RateLimit-Custom-Header", "Some value")
    }
}

定义速率限制作用域 ​

配置速率限制器后,可以使用 rateLimit() 函数将其应用于特定路由。

应用默认速率限制器 ​

使用不带名称的 rateLimit() 函数来应用默认注册的速率限制器:

kotlin
routing {
    rateLimit {
        get("/") {
            val requestsLeft = call.response.headers["X-RateLimit-Remaining"]
            call.respondText("Welcome to the home page! $requestsLeft requests left.")
        }
    }
}

应用命名速率限制器 ​

将 RateLimitName 传递给 rateLimit() 函数以应用命名速率限制器:

kotlin
routing {
    rateLimit(RateLimitName("protected")) {
        get("/protected-api") {
            val requestsLeft = call.response.headers["X-RateLimit-Remaining"]
            val login = call.request.queryParameters["login"]
            call.respondText("Welcome to protected API, $login! $requestsLeft requests left.")
        }
    }
}

示例 ​

以下示例演示了如何对不同的路由应用不同的速率限制器。 它配置了:

  • 针对主页的默认速率限制器。
  • 针对公共 API 的命名为 public 的速率限制器。
  • 使用请求键和权重的命名为 protected 的速率限制器。
  • 按客户端 IP 以及按 X-Api-Key 标头作为键的命名速率限制器。
  • 使用 StatusPages 插件自定义因 429 Too Many Requests 响应被拒绝的请求的响应内容。
kotlin
package com.example

import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.plugins.*
import io.ktor.server.plugins.ratelimit.*
import io.ktor.server.plugins.statuspages.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import kotlin.time.Duration.Companion.seconds

fun main(args: Array<String>): Unit = io.ktor.server.netty.EngineMain.main(args)

fun Application.module() {
    install(RateLimit) {
        register {
            rateLimiter(limit = 5, refillPeriod = 60.seconds)
        }
        register(RateLimitName("public")) {
            rateLimiter(limit = 10, refillPeriod = 60.seconds)
        }
        register(RateLimitName("protected")) {
            rateLimiter(limit = 30, refillPeriod = 60.seconds)
            requestKey { applicationCall ->
                applicationCall.request.queryParameters["login"]!!
            }
            requestWeight { applicationCall, key ->
                when (key) {
                    "jetbrains" -> 1
                    else -> 2
                }
            }
        }
        register(RateLimitName("per-ip")) {
            rateLimiter(limit = 5, refillPeriod = 60.seconds)
            requestKey { call ->
                call.request.origin.remoteHost
            }
        }
        register(RateLimitName("per-api-key")) {
            rateLimiter(limit = 5, refillPeriod = 60.seconds)
            requestKey { call ->
                call.request.headers["X-Api-Key"] ?: "anonymous"
            }
        }
    }
    install(StatusPages) {
        status(HttpStatusCode.TooManyRequests) { call, status ->
            val retryAfter = call.response.headers["Retry-After"]
            call.respondText(text = "429: Too many requests. Wait for $retryAfter seconds.", status = status)
        }
    }
    routing {
        rateLimit {
            get("/") {
                val requestsLeft = call.response.headers["X-RateLimit-Remaining"]
                call.respondText("Welcome to the home page! $requestsLeft requests left.")
            }
        }
        rateLimit(RateLimitName("public")) {
            get("/public-api") {
                val requestsLeft = call.response.headers["X-RateLimit-Remaining"]
                call.respondText("Welcome to public API! $requestsLeft requests left.")
            }
        }
        rateLimit(RateLimitName("protected")) {
            get("/protected-api") {
                val requestsLeft = call.response.headers["X-RateLimit-Remaining"]
                val login = call.request.queryParameters["login"]
                call.respondText("Welcome to protected API, $login! $requestsLeft requests left.")
            }
        }
        rateLimit(RateLimitName("per-ip")) {
            get("/ip-api") {
                val requestsLeft = call.response.headers["X-RateLimit-Remaining"]
                val clientHost = call.request.origin.remoteHost
                call.respondText("Welcome to IP API, $clientHost! $requestsLeft requests left.")
            }
        }
        rateLimit(RateLimitName("per-api-key")) {
            get("/keyed-api") {
                val requestsLeft = call.response.headers["X-RateLimit-Remaining"]
                val apiKey = call.request.headers["X-Api-Key"] ?: "anonymous"
                call.respondText("Welcome to keyed API, $apiKey! $requestsLeft requests left.")
            }
        }
    }
}

有关完整示例,请参阅 rate-limit。