如何使用 Spring Boot 在 Java 中构建 GraphQL 服务

让我们开始快速看一下所涉及的技术。

GraphQL

与REST相比,GraphQL是这个领域的新生事物,但是我认为它的改进是如此之大,以至于我正在开发新的api来使用它。我见过很多api在用户只需要一组标识符来遍历并查询与这些标识符相关的其他数据时返回了大量数据,这就突出了第二个问题。只是写这听起来很疯狂,我只是想做一个调用的API,并得到一切我所需要的。

我不会详细介绍GraphQL为什么会更好的原因,这里有很多文章可以让您自己决定。我要说的是,我决定进行转换的主要原因有两个:能够轻松地在请求中包含要接收的数据结构的能力;以及将多个REST请求合并为一个GraphQL查询的功能。两者都是对REST的巨大改进。当然,您可以尝试以这种方式编写REST端点,但是后来它们不再是REST了,因此GraphQL就是以这种方式工作的。

好了,现在已经不成问题了,让我们继续编写一些代码。我们将使用Spring Boot在Java中构建一个简单的GraphQL API准系统

Spring Boot

来自PHP的背景知识,我直到最近才发现Spring框架特别是Spring Boot的乐趣。这使得建立新项目变得非常容易。对如何为控制器、数据访问等配置和构造许多传统样板代码持固执己见的观点,但是当您想要按自己的方式进行配置时,它会变得毫无意义。在这个例子中,我们不需要编写任何控制器;只是我们的实体模型、类型和GraphQL模式。

先决条件

对于这个项目,我们将使用Java 8,我尝试使用Java 10,然后使用9,但是lombok的依赖关系存在问题,因此本教程必须降级为8。修复后,我将其更新为10。我们将使用Spring Boot 2,它使用Spring Framework的版本5,并为您进行全部设置。为简单起见,我们还将使用Maven构建框架来管理Java依赖项。我们还将使用出色的GraphQL-Java库spring boot starter来为我们提供GraphQL和GraphIQL端点(稍后会详细介绍)。最后,我添加了Project Lombok,它允许您注释类、方法、变量等来提供样板功能。

这是我将使用的确切版本:

  • Java 8(1.8.0_172)
  • Spring Boot 2.0.2
  • GraphQL-Java Spring Boot Starter 4.0.0
  • Maven 3.5.2
  • 龙目岛项目1.16.20

来,我们一起!

本教程的所有代码都可以在GitHub上找到

首先,创建一个新文件夹并在您选择的IDE中打开它。我正在使用Microsoft Visual Studio Code。抱歉,这确实是最好的免费代码编辑器。

创建一个名为pom.xml的新文件,并将其放入其中:


 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">
    4.0.0
 
    uk.co.benskin
    graphql_spring_boot_tutorial
    0.0.1-SNAPSHOT
    jar
 
    graphql_spring_boot_tutorial
    Learn how to build a graphql spring boot based java service
 
    
        org.springframework.boot
        spring-boot-starter-parent
        2.0.2.RELEASE
        
    
 
    
        UTF-8
        UTF-8
        1.8
    
 
    
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.springframework.boot
            spring-boot-devtools
        
        
            com.graphql-java
            graphql-java-tools
            4.3.0
        
        
            com.graphql-java
            graphql-spring-boot-starter
            4.0.0
        
        
            com.graphql-java
            graphiql-spring-boot-starter
            4.0.0
        
        
            org.projectlombok
            lombok
            1.16.20
        
    

上面的文件在上半年定义了我们的项目,因此将项目名称、描述等更改为您自己的项目详细信息。在下半年,我们定义了六个依赖项:

  • Spring Boot Web-提供通过Web协议支持我们的端点的功能
  • Spring Boot DevTools-对开发构建和调试很有用
  • GraphQL-Java工具-加载并驱动我们的GraphQL模式
  • 用于GraphQL的GraphQL-Java Spring引导启动程序-在我们的Spring上下文中的/ graphql端点上承载我们的模式
  • 用于GraphIQL的GraphQL-Java Spring引导启动程序-基于Web的UI,可与/ graphql端点进行交互,并了解端点处的模式
  • Lombok项目,用于减少Java代码中的样板

继续并安装所有依赖项

mvn install

首次安装依赖项产生大量输出之后,您应该看到一条消息,显示“ BUILD SUCCESS”。

好的,现在我们已经具备了开始所需的一切。

建立资料夹

src/main/java/uk/co/benskin/graphql_spring_boot_tutorial/

在其中创建一个文件

GraphQLSpringBootTutorialApplication.java

放入以下内容

package uk.co.benskin.graphql_spring_boot_tutorial;
 
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
 
@SpringBootApplication
public class GraphQLSpringBootTutorialApplication {
 
    public static void main(String[] args) {
        SpringApplication.run(GraphQLSpringBootTutorialApplication.class, args);
    }
}

这将加载一个新的Spring Applicaton Context,该上下文自动与我们的GraphQL-Java启动程序相关性集成。

现在,让我们尝试启动我们的应用程序,看看我们能得到什么

mvn spring-boot:run

您应该看到很多信息输出,希望有几行说

INFO 64612 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
INFO 64612 --- [  restartedMain] b.g.GraphQLSpringBootTutorialApplication : Started GraphQLSpringBootTutorialApplication in 4.886 seconds (JVM

现在打开浏览器,然后转到http:// localhost:8080

您应该会看到这样的错误页面

Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
 
[DATE]
There was an unexpected error (type=Not Found, status=404).
No message available

很好!服务器正在运行,但是我们还没有告诉我们如何在根目录“ /”处响应请求,因此,现在尝试http:// localhost:8080 / graphiql,您应该会看到一个不错的UI,用于与您的(到目前为止,待建)端点。

建立GraphQL模式

现在进入有趣的部分,即GraphQL模式。我不会详细介绍GraphQL的工作原理,请查看GraphQL教程。

建立这个档案

src/main/resources/petshop.graphqls

并在下面的内容

type Query {
    pets: [Pet]
}
 
type Pet {
    id: Int
    type: Animal
    name: String
    age: Int
}
 
enum Animal {
    DOG
    CAT
    BADGER
    MAMMOTH
}

上面我们定义了主查询,该查询将以Pet类型数组的形式返回“ pets”。Pet的类型是在其下定义的Animal类型的枚举。

构建API

现在返回到Java代码。我们将创建一些文件夹来帮助我们整理代码。对于这些名称以及它们的放置位置没有任何限制,但是我强烈建议您使用子文件夹来更好地组织代码,无数的未来开发人员将感谢您。

建立这个资料夹

src/main/java/uk/co/benskin/graphql_spring_boot_tutorial/enums

并创建此文件

src/main/java/uk/co/benskin/graphql_spring_boot_tutorial/enums/Animal.java

这是内容

package uk.co.benskin.graphql_spring_boot_tutorial.enums;
 
public enum Animal {
    DOG,
    CAT,
    BADGER,
    MAMMOTH
}

定义了我们的枚举,现在到Pet实体模型上

建立这个资料夹

src/main/java/uk/co/benskin/graphql_spring_boot_tutorial/entities

建立这个档案

src/main/java/uk/co/benskin/graphql_spring_boot_tutorial/entities/Pet.java

这是内容

package uk.co.benskin.graphql_spring_boot_tutorial.entities;
 
import lombok.Data;
import uk.co.benskin.graphql_spring_boot_tutorial.enums.Animal;
 
@Data
public class Pet {
    private long id;
 
    private String name;
 
    private Animal type;
 
    private int age;
}

这是一个带有@Data批注的简单POJO,用于处理样板获取器,设置器和构造函数。

现在为GraphQL解析器创建目录

src/main/java/uk/co/benskin/graphql-spring-boot-tutorial/resolvers

并创建文件

src/main/java/uk/co/benskin/graphql_spring_boot_tutorial/resolvers/Query.java

并用这个填充

package uk.co.benskin.graphql_spring_boot_tutorial.resolvers;
 
import java.util.ArrayList;
import java.util.List;
import com.coxautodev.graphql.tools.GraphQLQueryResolver;
import org.springframework.stereotype.Component;
import uk.co.benskin.graphql_spring_boot_tutorial.entities.Pet;
import uk.co.benskin.graphql_spring_boot_tutorial.enums.Animal;
 
@Component
public class Query implements GraphQLQueryResolver {
 
    public List<Pet> pets() {
        List<Pet> pets = new ArrayList<>();
 
        Pet aPet = new Pet();
        aPet.setId(1l);
        aPet.setName("Bill");
        aPet.setAge(9);
        aPet.setType(Animal.MAMMOTH);
 
        pets.add(aPet);
 
        return pets;
    }
}

好的,这应该是我们调用GraphQL端点以获得宠物列表所需的一切(本例中为一只)

通过停止Maven(ctrl / cmd + c)并使用mvn spring-boot:run重新启动来重新启动构建

要查看其运行情况,请访问http:// localhost:8080 / graphiql,您将获得一个不错的UI。同样,我将不对如何使用GraphIQL接口进行详细介绍。

在“历史记录”框右侧的GraphIQL标题正下方的框中,您可以在其中输入请求。将以下内容复制并粘贴到此处:

{
    pets {
        name
        age
        type
    }
}

然后单击播放图标(GraphIQL标题旁边)。您应该看到如下响应:

{
    "data": {
        "pets": [
            {
                "name": "Bill",
                "age": 9,
                "type": "MAMMOTH"
            }
        ]
    }
}

恭喜你!您刚刚用Java和SpringBoot编写了GraphQL服务。好的,因此除了该一条记录外,它不会返回任何其他内容,因此在第2部分中,我们通过Spring Data项目介绍了数据库访问,该项目利用了Java Persistence API(JPA)

非常感谢您阅读本文!

原文链接:https://dev.to//sambenskin/howto-build-graphql-services-in-java-with-spring-boot---part-1-38b2

你可能感兴趣的:(spring,boot)