Ktor 服务器模式 是做什么的?
全面的 Ktor 模式,用于使用 Kotlin 协程构建健壮、可维护的 HTTP 服务器。
何时激活
- 构建 Ktor HTTP 服务器
- 配置 Ktor 插件(认证、CORS、内容协商、StatusPages)
- 使用 Ktor 实现 REST API
- 使用 Koin 设置依赖注入
- 使用 testApplication 编写 Ktor 集成测试
- 在 Ktor 中使用 WebSocket
应用结构
标准 Ktor 项目布局
src/main/kotlin/
├── com/example/
│ ├── Application.kt # 入口点、模块配置
│ ├── plugins/
│ │ ├── Routing.kt # 路由定义
│ │ ├── Serialization.kt # 内容协商设置
│ │ ├── Authentication.kt # 认证配置
│ │ ├── StatusPages.kt # 错误处理
│ │ └── CORS.kt # CORS 配置
│ ├── routes/
│ │ ├── UserRoutes.kt # /users 端点
│ │ ├── AuthRoutes.kt # /auth 端点
│ │ └── HealthRoutes.kt # /health 端点
│ ├── models/
│ │ ├── User.kt # 领域模型
│ │ └── ApiResponse.kt # 响应包装
│ ├── services/
│ │ ├── UserService.kt # 业务逻辑
│ │ └── AuthService.kt # 认证逻辑
│ ├── repositories/
│ │ ├── UserRepository.kt # 数据访问接口
│ │ └── ExposedUserRepository.kt
│ └── di/
│ └── AppModule.kt # Koin 模块
src/test/kotlin/
├── com/example/
│ ├── routes/
│ │ └── UserRoutesTest.kt
│ └── services/
│ └── UserServiceTest.kt
应用入口点
// Application.kt
fun main() {
embeddedServer(Netty, port = 8080, module = Application::module).start(wait = true)
}
fun Application.module() {
configureSerialization()
configureAuthentication()
configureStatusPages()
configureCORS()
configureDI()
configureRouting()
}
路由 DSL
基本路由
// plugins/Routing.kt
fun Application.configureRouting() {
routing {
userRoutes()
authRoutes()
healthRoutes()
}
}
// routes/UserRoutes.kt
fun Route.userRoutes() {
val userService by inject<UserService>()
route("/users") {
get {
val users = userService.getAll()
call.respond(users)
}
get("/{id}") {
val id = call.parameters["id"]
?: return@get call.respond(HttpStatusCode.BadRequest, "Missing id")
val user = userService.getById(id)
?: return@get call.respond(HttpStatusCode.NotFound)
call.respond(user)
}
post {
val request = call.receive<CreateUserRequest>()
val user = userService.create(request)
call.respond(HttpStatusCode.Created, user)
}
put("/{id}") {
val id = call.parameters["id"]
?: return@put call.respond(HttpStatusCode.BadRequest, "Missing id")
val request = call.receive<UpdateUserRequest>()
val user = userService.update(id, request)
?: return@put call.respond(HttpStatusCode.NotFound)
call.respond(user)
}
delete("/{id}") {
val id = call.parameters["id"]
?: return@delete call.respond(HttpStatusCode.BadRequest, "Missing id")
val deleted = userService.delete(id)
if (deleted) call.respond(HttpStatusCode.NoContent)
else call.respond(HttpStatusCode.NotFound)
}
}
}
带认证路由的路由组织
fun Route.userRoutes() {
route("/users") {
// 公共路由
get { /* 列出用户 */ }
get("/{id}") { /* 获取用户 */ }
// 受保护路由
authenticate("jwt") {
post { /* 创建用户 - 需要认证 */ }
put("/{id}") { /* 更新用户 - 需要认证 */ }
delete("/{id}") { /* 删除用户 - 需要认证 */ }
}
}
}
内容协商与序列化
kotlinx.serialization 设置
// plugins/Serialization.kt
fun Application.configureSerialization() {
install(ContentNegotiation) {
json(Json {
prettyPrint = true
isLenient = false
ignoreUnknownKeys = true
encodeDefaults = true
explicitNulls = false
})
}
}
可序列化模型
@Serializable
data class UserResponse(
val id: String,
val name: String,
val email: String,
val role: Role,
@Serializable(with = InstantSerializer::class)
val createdAt: Instant,
)
@Serializable
data class CreateUserRequest(
val name: String,
val email: String,
val role: Role = Role.USER,
)
@Serializable
data class ApiResponse<T>(
val success: Boolean,
val data: T? = null,
val error: String? = null,
) {
companion object {
fun <T> ok(data: T): ApiResponse<T> = ApiResponse(success = true, data = data)
fun <T> error(message: String): ApiResponse<T> = ApiResponse(success = false, error = message)
}
}
@Serializable
data class PaginatedResponse<T>(
val data: List<T>,
val total: Long,
val page: Int,
val limit: Int,
)
自定义序列化器
object InstantSerializer : KSerializer<Instant> {
override val descriptor = PrimitiveSerialDescriptor("Instant", PrimitiveKind.STRING)
override fun serialize(encoder: Encoder, value: Instant) =
encoder.encodeString(value.toString())
override fun deserialize(decoder: Decoder): Instant =
Instant.parse(decoder.decodeString())
}
认证
JWT 认证
// plugins/Authentication.kt
fun Application.configureAuthentication() {
val jwtSecret = environment.config.property("jwt.secret").getString()
val jwtIssuer = environment.config.property("jwt.issuer").getString()
val jwtAudience = environment.config.property("jwt.audience").getString()
val jwtRealm = environment.config.property("jwt.realm").getString()
install(Authentication) {
jwt("jwt") {
realm = jwtRealm
verifier(
JWT.require(Algorithm.HMAC256(jwtSecret))
.withAudience(jwtAudience)
.withIssuer(jwtIssuer)
.build()
)
validate { credential ->
if (credential.payload.audience.contains(jwtAudience)) {
JWTPrincipal(credential.payload)
} else {
null
}
}
challenge { _, _ ->
call.respond(HttpStatusCode.Unauthorized, ApiResponse.error<Unit>("无效或过期的令牌"))
}
}
}
}
// 从 JWT 提取用户
fun ApplicationCall.userId(): String =
principal<JWTPrincipal>()
?.payload
?.getClaim("userId")
?.asString()
?: throw AuthenticationException("令牌中缺少 userId")
认证路由
fun Route.authRoutes() {
val authService by inject<AuthService>()
route("/auth") {
post("/login") {
val request = call.receive<LoginRequest>()
val token = authService.login(request.email, request.password)
?: return@post call.respond(
HttpStatusCode.Unauthorized,
ApiResponse.error<Unit>("凭据无效"),
)
call.respond(ApiResponse.ok(TokenResponse(token)))
}
post("/register") {
val request = call.receive<RegisterRequest>()
val user = authService.register(request)
call.respond(HttpStatusCode.Created, ApiResponse.ok(user))
}
authenticate("jwt") {
get("/me") {
val userId = call.userId()
val user = authService.getProfile(userId)
call.respond(ApiResponse.ok(user))
}
}
}
}
StatusPages(错误处理)
// plugins/StatusPages.kt
fun Application.configureStatusPages() {
install(StatusPages) {
exception<ContentTransformationException> { call, cause ->
call.respond(
HttpStatusCode.BadRequest,
ApiResponse.error<Unit>("无效的请求体: ${cause.message}"),
)
}
exception<IllegalArgumentException> { call, cause ->
call.respond(
HttpStatusCode.BadRequest,
ApiResponse.error<Unit>(cause.message ?: "错误的请求"),
)
}
exception<AuthenticationException> { call, _ ->
call.respond(
HttpStatusCode.Unauthorized,
ApiResponse.error<Unit>("需要认证"),
)
}
exception<AuthorizationException> { call, _ ->
call.respond(
HttpStatusCode.Forbidden,
ApiResponse.error<Unit>("访问被拒绝"),
)
}
exception<NotFoundException> { call, cause ->
call.respond(
HttpStatusCode.NotFound,
ApiResponse.error<Unit>(cause.message ?: "资源未找到"),
)
}
exception<Throwable> { call, cause ->
call.application.log.error("未处理的异常", cause)
call.respond(
HttpStatusCode.InternalServerError,
ApiResponse.error<Unit>("内部服务器错误"),
)
}
status(HttpStatusCode.NotFound) { call, status ->
call.respond(status, ApiResponse.error<Unit>("路由未找到"))
}
}
}
CORS 配置
// plugins/CORS.kt
fun Application.configureCORS() {
install(CORS) {
allowHost("localhost:3000")
allowHost("example.com", schemes = listOf("https"))
allowHeader(HttpHeaders.ContentType)
allowHeader(HttpHeaders.Authorization)
allowMethod(HttpMethod.Put)
allowMethod(HttpMethod.Delete)
allowMethod(HttpMethod.Patch)
allowCredentials = true
maxAgeInSeconds = 3600
}
}
Koin 依赖注入
模块定义
// di/AppModule.kt
val appModule = module {
// 数据库
single<Database> { DatabaseFactory.create(get()) }
// 仓库
single<UserRepository> { ExposedUserRepository(get()) }
single<OrderRepository> { ExposedOrderRepository(get()) }
// 服务
single { UserService(get()) }
single { OrderService(get(), get()) }
single { AuthService(get(), get()) }
}
// 应用设置
fun Application.configureDI() {
install(Koin) {
modules(appModule)
}
}
在路由中使用 Koin
fun Route.userRoutes() {
val userService by inject<UserService>()
route("/users") {
get {
val users = userService.getAll()
call.respond(ApiResponse.ok(users))
}
}
}
Koin 用于测试
class UserServiceTest : FunSpec(), KoinTest {
override fun extensions() = listOf(KoinExtension(testModule))
private val testModule = module {
single<UserRepository> { mockk() }
single { UserService(get()) }
}
private val repository by inject<UserRepository>()
private val service by inject<UserService>()
init {
test("getUser 返回用户") {
coEvery { repository.findById("1") } returns testUser
service.getById("1") shouldBe testUser
}
}
}
请求验证
// 在路由中验证请求数据
fun Route.userRoutes() {
val userService by inject<UserService>()
post("/users") {
val request = call.receive<CreateUserRequest>()
// 验证
require(request.name.isNotBlank()) { "名称不能为空" }
require(request.name.length <= 100) { "名称不能超过100个字符" }
require(request.email.matches(Regex(".+@.+\\..+"))) { "邮箱格式无效" }
val user = userService.create(request)
call.respond(HttpStatusCode.Created, ApiResponse.ok(user))
}
}
// 或者使用验证扩展
fun CreateUserRequest.validate() {
require(name.isNotBlank()) { "名称不能为空" }
require(name.length <= 100) { "名称不能超过100个字符" }
require(email.matches(Regex(".+@.+\\..+"))) { "邮箱格式无效" }
}
WebSocket
fun Application.configureWebSockets() {
install(WebSockets) {
pingPeriod = 15.seconds
timeout = 15.seconds
maxFrameSize = 64 * 1024 // 64 KiB — 仅当协议需要更大帧时才增加
masking = false // 根据RFC 6455,服务器到客户端的帧不被掩码;客户端到服务器的帧始终由Ktor掩码
}
}
fun Route.chatRoutes() {
val connections = Collections.synchronizedSet<Connection>(LinkedHashSet())
webSocket("/chat") {
val thisConnection = Connection(this)
connections += thisConnection
try {
send("已连接!在线用户: ${connections.size}")
for (frame in incoming) {
frame as? Frame.Text ?: continue
val text = frame.readText()
val message = ChatMessage(thisConnection.name, text)
// 在锁下快照以避免 ConcurrentModificationException
val snapshot = synchronized(connections) { connections.toList() }
snapshot.forEach { conn ->
conn.session.send(Json.encodeToString(message))
}
}
} catch (e: Exception) {
logger.error("WebSocket 错误", e)
} finally {
connections -= thisConnection
}
}
}
data class Connection(val session: DefaultWebSocketSession) {
val name: String = "用户-${counter.getAndIncrement()}"
…
[已截断以进行翻译]
## 集成测试
```kotlin
class UserRoutesTest {
@Test
fun `test create user`() = testApplication {
application {
module()
}
val client = createClient {
install(ContentNegotiation) {
json()
}
}
val response = client.post("/users") {
contentType(ContentType.Application.Json)
setBody(CreateUserRequest("John", "[email protected]"))
}
assertEquals(HttpStatusCode.Created, response.status)
val user = response.body<UserResponse>()
assertNotNull(user.id)
assertEquals("John", user.name)
}
}
性能与部署
配置驱动设置
// application.conf
ktor {
deployment {
port = 8080
host = 0.0.0.0
environment = production
}
application {
modules = [ com.example.ApplicationKt.module ]
}
}
jwt {
secret = "your-secret-key"
issuer = "your-issuer"
audience = "your-audience"
realm = "your-realm"
}
性能最佳实践
- 启用连接池
- 使用协程上下文调度
- 配置适当的连接超时
- 在适当的情况下使用静态内容处理
- 实施响应缓存