简介
Graphql 是一种类似于 REST 的一种 API 标准。
不是一种数据库技术。
总的来说就是,后端可以根据前端需要的字段返回对应的信息,不需要修改原有接口。
--- 1.前端请求字段
{
hero {
name
}
}
--- 2.后端返回结果
{
"data": {
"hero": {
"name": "R2-D2"
}
}
}
--- 1.前端请求字段
{
hero {
name
# Queries can have comments!
friends {
name
}
}
}
--- 2.后端返回结果
{
"data": {
"hero": {
"name": "R2-D2",
"friends": [
{
"name": "Luke Skywalker"
},
{
"name": "Han Solo"
},
{
"name": "Leia Organa"
}
]
}
}
}
demo
https://gitee.com/hitol/graphql-demo.git
dependencies
<dependency>
<groupId>com.graphql-java</groupId>
<artifactId>graphql-java</artifactId>
<version>11.0</version>
</dependency>
<dependency>
<groupId>com.graphql-java</groupId>
<artifactId>graphiql-spring-boot-starter</artifactId>
<version>3.10.0</version>
</dependency>
<dependency>
<groupId>com.graphql-java</groupId>
<artifactId>graphql-java-spring-boot-starter-webmvc</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>26.0-jre</version>
</dependency>
Schema
在 resources 文件夹下新建一个 schema.graphqls 文件,其内容如下
type Query {
bookById(id: ID): Book
}
type Book {
id: ID
name: String
pageCount: Int
author: Author
}
type Author {
id: ID
firstName: String
lastName: String
}
Graphql 加载到 Spring
@Component
public class GraphQLProvider {
@Autowired
GraphQLDataFetchers graphQLDataFetchers;
private GraphQL graphQL;
@PostConstruct
public void init() throws IOException {
URL url = Resources.getResource("schema.graphqls");
String sdl = Resources.toString(url, Charsets.UTF_8);
GraphQLSchema graphQLSchema = buildSchema(sdl);
this.graphQL = GraphQL.newGraphQL(graphQLSchema).build();
}
private GraphQLSchema buildSchema(String sdl) {
TypeDefinitionRegistry typeRegistry = new SchemaParser().parse(sdl);
RuntimeWiring runtimeWiring = buildWiring();
SchemaGenerator schemaGenerator = new SchemaGenerator();
return schemaGenerator.makeExecutableSchema(typeRegistry, runtimeWiring);
}
private RuntimeWiring buildWiring() {
return RuntimeWiring.newRuntimeWiring()
.type(newTypeWiring("Query")
.dataFetcher("bookById", graphQLDataFetchers.getBookByIdDataFetcher()))
.type(newTypeWiring("Book")
.dataFetcher("author", graphQLDataFetchers.getAuthorDataFetcher()))
.build();
}
@Bean
public GraphQL graphQL() {
return graphQL;
}
}
其中对于文件的解析 最重要的方法就是 buildWiring
这一块其实就是后端提供的关于 graphql 的接口。
使用了一个插件,方便调试 graphiql
项目启动之后浏览器中访问,http://localhost:8080/graphiql

https://www.graphql-java.com/tutorials/getting-started-with-spring-boot/
