GraphQL介绍
GraphQL(Graph Query Language)是一种用于API的查询语言和运行时环境,由Facebook于2012年创建并在2015年公开发布。与传统的RESTful API相比,GraphQL提供了更灵活、高效和强大的数据查询和操作方式。
以下是GraphQL的一些主要特点和概念:
- 灵活性: 客户端可以精确指定需要的数据,而不会获得多余或不需要的信息。这允许前端应用程序更有效地获取所需的数据,减少了不必要的数据传输和处理。
- 单一端点: 与RESTful API不同,GraphQL通常只有一个端点,客户端可以在一个请求中指定所需的所有数据。这消除了多个端点的复杂性,提高了请求效率。
- 强类型系统: GraphQL具有明确定义的数据类型,客户端和服务器之间的通信是基于这些类型的。这使得开发更容易,并减少了潜在的通信错误。
- 关联和嵌套查询: 可以在一个请求中同时获取关联的数据,而不需要多个请求。这样可以减少网络延迟,并提高性能。
- 实时数据: GraphQL支持实时数据传输,使得客户端能够订阅数据的变化,从而实时更新界面。
- 文档性: GraphQL有强大的自描述能力,通过introspection可以获取API的详细信息。这样可以轻松创建自动化工具,例如自动生成文档或客户端代码。
- 版本控制: GraphQL允许在API中逐步添加新字段和类型,而不会破坏现有客户端的功能。这降低了版本迁移的难度。
GraphQL的基本概念包括:
- 查询(Query): 定义客户端请求的数据结构,以及所需的字段和关联关系。
- 变更(Mutation): 用于对数据进行写操作的请求,例如创建、更新或删除数据。
- 订阅(Subscription): 允许客户端接收实时数据的推送,使得应用程序能够立即响应数据的变化。
- 类型系统: 定义API中所有可能的数据类型,包括标量(Scalar)、对象(Object)、枚举(Enum)等。
pom依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>spring-boot-test</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<spring-boot.version>2.7.11</spring-boot.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-graphql</artifactId>
<version>${spring-boot.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>${spring-boot.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
<version>${spring-boot.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</project>
实体类
两个实体类:Book 和 Author
package com.testcode.model;
import java.util.Arrays;
import java.util.List;
public class Author {
private String id;
private String firstName;
private String lastName;
public Author(String id, String firstName, String lastName) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
private static List<Author> authors = Arrays.asList(
new Author("author-1", "Joanne", "Rowling"),
new Author("author-2", "Herman", "Melville"),
new Author("author-3", "Anne", "Rice")
);
public static Author getById(String id) {
return authors.stream().filter(author -> author.getId().equals(id)).findFirst().orElse(null);
}
public String getId() {
return id;
}
}
package com.testcode.model;
import java.util.Arrays;
import java.util.List;
public class Book {
private String id;
private String name;
private int pageCount;
private String authorId;
public Book(String id, String name, int pageCount, String authorId) {
this.id = id;
this.name = name;
this.pageCount = pageCount;
this.authorId = authorId;
}
private static List<Book> books = Arrays.asList(
new Book("book-1", "Harry Potter and the Philosopher's Stone", 223, "author-1"),
new Book("book-2", "Moby Dick", 635, "author-2"),
new Book("book-3", "Interview with the vampire", 371, "author-3")
);
public static Book getById(String id) {
return books.stream().filter(book -> book.getId().equals(id)).findFirst().orElse(null);
}
public String getId() {
return id;
}
public String getAuthorId() {
return authorId;
}
}
Controller
package com.testcode.controller;
import com.testcode.model.Author;
import com.testcode.model.Book;
import org.springframework.graphql.data.method.annotation.Argument;
import org.springframework.graphql.data.method.annotation.QueryMapping;
import org.springframework.graphql.data.method.annotation.SchemaMapping;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;
@Controller
public class BookController {
@QueryMapping
public Book bookById(@Argument String id) {
return Book.getById(id);
}
@SchemaMapping
public Author author(Book book) {
return Author.getById(book.getAuthorId());
}
}
application.yml配置
server:
port: 9999
spring:
graphql:
graphiql:
path: /graphiql
enabled: true
启动类
package com.testcode;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import java.util.Arrays;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
浏览器访问调试窗口
http://localhost:9999/graphiql?path=/graphql
输入查询语句:
query bookDetails {
bookById(id: "book-3") {
id
name
pageCount
author {
key:id -- 别名映射
firstName
lastName
}
}
}