GraphQl介绍
-
- GraphQL 查询时结构化的,信息是类树结构展示的。值类型可以理解为叶子,对象类型可以理解为树干
- GraphQL 是一种描述如何请求数据的语法,通常用于客户端向服务器请求数据。
- GraphQL 层位于客户端和一个或多个数据源之间,按照你的指示接收客户端请求,然后获取必要的数据。
- GraphQL API 围绕三个主要构建块组织:模式(schema)、查询(query)、解析器(resolver)。
- GraphQL 只是一个规范
-
特点
- 允许客户端精确指定所需数据。
- 可以更容易地从多个数据源聚合数据。
- 使用类型系统描述数据。
作者:666真666
链接:https://www.jianshu.com/p/e76eb5393a2b
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
准备工作
你需要检查自己的环境是否满足以下前提。你可以打开终端,使用以下命令检测自己是否已经安装JDK 、Kotlin 和 gradle 。
$ kotlin -version
## output: Kotlin version 1.3.61-release-180 (JRE 13.0.2+8)
$ javac -version
## output: javac 13.0.2
$ gradle -version
使用 Spring Boot Initializr 生成项目
访问 https://start.spring.io/ , 选择如下的环境:
-
Project: Gradle Project
-
Language: Kotlin
-
Spring Boot: 2.2.5
-
Group: com.springforall
-
Artifact: graphqlDemo
-
Dependencies: Spring Web, Spring Boot DevTools
选择完成之后,点击生成按钮。
添加依赖
我们需要添加GraphQL的相关依赖和工具。
// file build.gradle.kts
dependencies {
implementation ("com.graphql-java:graphql-spring-boot-starter:5.0.2")
implementation ("com.graphql-java:graphiql-spring-boot-starter:5.0.2")
implementation ("com.graphql-java:voyager-spring-boot-starter:5.0.2")
implementation ("com.graphql-java:graphql-java-tools:5.2.4")
// ... rest of dependencies
}
这里我们已经在项目中集成了 graphql, https://github.com/graphql/graphiql#graphiql, https://github.com/APIs-guru/graphql-voyager 这些工具可以更好的帮助你使用GraphiQL设计类的关系和结构。
修改应用配置
通过上面添加依赖后,我们需要对GraphiQL做相关的配置。创建一个配置文件,配置文件的名称根据约定优于配置的原则,暂且命名为 application.yml
在 ./src/main/resources
# file application.yml
graphql:
servlet:
mapping: /graphql
enabled: true
corsEnabled: true
graphiql:
mapping: /graphiql
endpoint: /graphql
enabled: true
pageTitle: GraphiQL
cdn:
enabled: false
version: 0.11.11
数据模型
现在我们创建一个数据模型类,类名为Book,此类包含两个属性。
package com.springforall.graphqlDemo
data class Book( val id: String, val name: String )
// file: ./src/main/kotlin/com/grekz/graphqlDemo/Book.kt
创建 GraphQL 查询解析器
package com.springforall.graphqlDemo
import org.springframework.stereotype.Component
import com.coxautodev.graphql.tools.GraphQLQueryResolver
@Component
class BookResolver() : GraphQLQueryResolver {
// this method name needs to be same and in the schema
fun books(): List<Book> {
val book1 = Book("1", "name1")
val book2 = Book("2", "name2")
return listOf(book1, book2)
}
}
// file: ./src/main/kotlin/com/springforall/graphqlDemo/BookResolver.kt
定义 GraphQL schema
在 GraphQL 中,需要定义类型和数据如何被查询的规则。接下来在./src/main/resources/models.graphqls
进行相关定义。
type Query {
books: [Book]
}
type Book {
id: String!
name: String!
}
运行项目!
接下来我们开始运行项目,验证结果。可以使用如下命令启动项目:
$ gradle bootRun
也可以点击 “Debug” 按钮运行,验证结果。访问: http://localhost:8080/voyager ,检查是否正常。
这样我们便完成了在SpringBoot中如何集成 GraphQL 并运行。
文章经过本人加工,原文来自:SpringForAll社区