Kotlin 的 GraphQL 库:完整概述与实用指南
GraphQL 是一种 API 查询语言,它允许客户端只获取他们真正需要的数据。在 Kotlin 生态系统中,有几个强大的库可用于处理 GraphQL,无论是在服务器端还是客户端。在本文中,我们将介绍三个关键库:graphql-kotlin、KGraphQL 和 Apollo Kotlin,并展示它们的使用示例。
1. graphql-kotlin — Expedia Group 的官方库
graphql-kotlin 是在 Kotlin 上创建 GraphQL 服务器最成熟且维护良好的库。它充分利用了该语言的特性,例如协程、数据类和空安全。
主要功能:
- 支持 Kotlin 协程进行异步处理
- 从数据类自动生成模式
- 通过 WebSocket 内置支持订阅 (Subscriptions)
- 与 Spring Boot、Ktor 和其他框架集成
- 完全支持 GraphQL June 2018 规范
graphql-kotlin 服务器示例:
// 定义数据模型data class User(val id: String, val name: String, val email: String)
// 创建 Query 解析器class UserQuery : Query { fun getUser(id: String): User? { // 获取用户的逻辑 return User(id = "1", name = "伊万·彼得罗夫", email = "ivan@example.com") } fun users(): List<User> = listOf( User("1", "伊万", "ivan@example.com"), User("2", "玛丽亚", "maria@example.com") )}
// 配置并启动服务器fun main() { val schema = Schema { query(UserQuery()) } val server = GraphQLServer(schema) server.start(port = 8080)}客户端请求示例:
query { user(id: "1") { name email }}2. KGraphQL — 轻量级替代方案
KGraphQL 是一个用于创建 GraphQL API 的极简库。它的特点是配置简单且没有多余的依赖。
主要特点:
- 体积小 — 约 100 KB
- 不需要 Spring Boot 或其他重型框架
- 支持使用 DSL 定义模式
- 可与任何 HTTP 服务器集成
KGraphQL 使用示例:
// 定义模型data class Product(val id: Int, val title: String, val price: Double)
// 创建 GraphQL 模式val schema = schema { query("products") { resolver { -> listOf( Product(1, "笔记本电脑", 89999.99), Product(2, "鼠标", 2499.50) ) } } query("product") { resolver { id: Int -> Product(id, "商品 #$id", 1000.0) } }}
// 启动服务器fun main() { val server = KGraphQLServer(schema) server.start(port = 4000)}3. Apollo Kotlin — Apollo 的客户端库
Apollo Kotlin 是一个用于处理 GraphQL API 的强大客户端。它根据 GraphQL 模式生成类型安全的代码,大大简化了开发过程。
Apollo Kotlin 的优势:
- 从 .graphql 文件生成 Kotlin 代码
- 支持缓存(标准化缓存)
- 与协程和 Flow 配合使用
- 自动错误处理
- 支持变更、查询和订阅
Apollo Kotlin 客户端使用示例:
// 首先在 .graphql 文件中定义查询// file: GetUser.graphql// query GetUser($id: ID!) {// user(id: $id) {// id// name// email// }