Spring Boot 2.7.11 集成 GraphQL

GraphQL介绍

GraphQL(Graph Query Language)是一种用于API的查询语言和运行时环境,由Facebook于2012年创建并在2015年公开发布。与传统的RESTful API相比,GraphQL提供了更灵活、高效和强大的数据查询和操作方式。

以下是GraphQL的一些主要特点和概念:

  1. 灵活性: 客户端可以精确指定需要的数据,而不会获得多余或不需要的信息。这允许前端应用程序更有效地获取所需的数据,减少了不必要的数据传输和处理。
  2. 单一端点: 与RESTful API不同,GraphQL通常只有一个端点,客户端可以在一个请求中指定所需的所有数据。这消除了多个端点的复杂性,提高了请求效率。
  3. 强类型系统: GraphQL具有明确定义的数据类型,客户端和服务器之间的通信是基于这些类型的。这使得开发更容易,并减少了潜在的通信错误。
  4. 关联和嵌套查询: 可以在一个请求中同时获取关联的数据,而不需要多个请求。这样可以减少网络延迟,并提高性能。
  5. 实时数据: GraphQL支持实时数据传输,使得客户端能够订阅数据的变化,从而实时更新界面。
  6. 文档性: GraphQL有强大的自描述能力,通过introspection可以获取API的详细信息。这样可以轻松创建自动化工具,例如自动生成文档或客户端代码。
  7. 版本控制: 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
    }
  }
}

  • 6
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值