大家好,我是程序员柏风,AI 最全的 Vibecoding 学习地图 http://coderoadmap.cn 作者。
Ktor 服务端
Ktor 是 JetBrains 出品的 Kotlin 原生 Web 框架,协程优先、轻量灵活;Quarkus 等也支持 Kotlin,适合微服务与 API 网关。
学习目标
- 了解 Ktor 的基本路由与插件
- 会用协程处理 HTTP 请求
- 知道 Ktor 与 Spring Boot 的选型差异
Ktor 入门
import io.ktor.server.application.*
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.ktor.serialization.kotlinx.json.*
import io.ktor.server.plugins.contentnegotiation.*
import kotlinx.serialization.Serializable
@Serializable
data class Track(val slug: String, val title: String, val lessonCount: Int)
fun main() {
embeddedServer(Netty, port = 8080) {
install(ContentNegotiation) { json() }
routing {
get("/") {
call.respondText("Hello, CodeRoadMap!")
}
get("/api/tracks/{slug}") {
val slug = call.parameters["slug"] ?: return@get call.respondText("Missing slug", status = io.ktor.http.HttpStatusCode.BadRequest)
val track = findTrack(slug)
if (track != null) call.respond(track)
else call.respondText("Not found", status = io.ktor.http.HttpStatusCode.NotFound)
}
}
}.start(wait = true)
}
fun findTrack(slug: String): Track? =
if (slug == "kotlin-essentials") Track(slug, "Kotlin 语言入门", 12)
else null
embeddedServer 启动 Netty;routing 定义路由;ContentNegotiation 自动 JSON 序列化。
协程与文件 I/O
import io.ktor.server.application.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.File
fun Application.configureFileRoutes() {
routing {
get("/api/lessons/export") {
val content = withContext(Dispatchers.IO) {
File("lessons.json").readText()
}
call.respondText(content, contentType = io.ktor.http.ContentType.Application.Json)
}
}
}
阻塞 IO 用 withContext(Dispatchers.IO) 切换到 IO 调度器,不阻塞 Netty 事件线程。
Ktor vs Spring Boot
| 维度 | Ktor | Spring Boot |
|---|---|---|
| 风格 | 轻量、协程原生 | 全功能、生态成熟 |
| 学习曲线 | 低,代码量少 | 中,注解驱动 |
| 适用 | API 网关、微服务、原型 | 企业 CRUD、复杂业务 |
| 与 Java 生态 | 可集成 Exposed、Koin | 无缝用 MyBatis、JPA |
CodeRoadMap 主线仍是 Spring Boot;Ktor 适合 Kotlin 原生小服务或学习协程 Web 编程。
与 Java 对照
| Ktor | Spring Boot (Java) |
|---|---|
routing { get { } } | @GetMapping |
call.respond(dto) | return ResponseEntity.ok(dto) |
install(Plugin) | @Configuration + Bean |
withContext(IO) | @Async / Virtual Thread |
| kotlinx.serialization | Jackson |
练习
- 用 Ktor 创建
/api/tracks返回 track 列表 JSON - 添加
POST /api/tracks接收 JSON 创建 track(内存存储即可) - 对比 Ktor 与 Spring Boot 的 Controller 写法
小结
Ktor = Kotlin 原生 + 协程 + 轻量 Web。 下一课综合练习。见 kotlin-essentials。