SpringBoot怎么使用GraphQL开发Web API

前言

传统的restful api 存在诸多的问题,首先它无法控制返回的字段,前端也无法预判后端的返回结果,另外不同的返回结果对应不同的请求地址,这就导致了多次请求的问题。而graphql正是基于这样的背景而构建出来的api查询语言,相对于传统restful api 它具有以下几个优点:

灵活性:GraphQL 可以根据客户端的需求灵活地查询数据,而不是像 RESTful API 那样返回固定结构的数据。

减少网络请求:GraphQL 允许客户端在一次请求中获取多个资源,这有助于减少网络请求的数量和提高性能。

强类型:GraphQL 有一种强类型系统,客户端可以在编译时检测到查询中的错误,这有助于减少运行时错误。

可缓存:GraphQL 具有可缓存性,这意味着服务器可以缓存查询的结果,从而提高性能和可伸缩性。

文档化:GraphQL 具有自我文档化的能力,使得开发者可以快速了解 API 的结构和功能。

Spring Boot中GraphQL的实现方案

如果后端语言为Java,那么GraphQL Java则是实现GraphQL的基础库。另外Spring已经整合了GraphQL,如果项目中使用了Spring,那么更加推荐Spring GraphQL。

Spring GraphQL的开发总体分为如下几个步骤

添加 Spring GraphQL 依赖项

在您的项目中添加 Spring GraphQL 依赖项。您可以通过 Maven 或 Gradle 等构建工具来添加依赖项。例如,如果您使用 Maven,则可以添加以下依赖项

                    org.springframework.boot            spring-boot-starter-graphql        

登录后复制

定义 GraphQL Schema

在您的应用程序中定义 GraphQL Schema。Schema 定义了可查询的类型和字段。您可以使用 SDL(Schema Definition Language)或编程方式定义 Schema。

对于Spring Boot 工程来说schema文件放到resources/graphql/目录下,文件名后缀graphqls,下面是我定义一个的简单的schema.graphqls。

它指定了两个查询实现,author(id:Int)表示通过id查询Author,allAuthors则表示查询Author数组。

schema {    query: Query}type Query {    author(id:Int): Author    allAuthors: [Author]}type Author {    id:Int    firstName:String    lastName:String    email:String    birthdate:String}

实现RuntimeWiringConfigurer

RuntimeWiringConfigurer是实现GraphQL获取数据的核心,使用GraphQL并不能直接去掉Mybatis/Jpa这类持久层框架,从数据库获取数据仍然需要这类框架的支持。

而RuntimeWiringConfigurer则类似于Spring中的service层,它是实现基础数据的核心。

以下是一个简单示例:

@Componentpublic class AuthorWiring implements RuntimeWiringConfigurer {    private final AuthorRepository authorRepository;    public AuthorWiring(AuthorRepository authorRepository) {        this.authorRepository = authorRepository;    }    @Override    public void configure(RuntimeWiring.Builder builder) {        builder.type("Query", typeWiring -> typeWiring                        .dataFetcher("allAuthors", environment -> authorRepository.findAll())                        .dataFetcher("author", environment -> authorRepository.getReferenceById(environment.getArgument("id")))    }}

登录后复制

这里configure方法内部分别定义了两个DataFetcher对象,用来指定author和allAuthors查询数据的方式,可以看出依然是通过JPA去查询数据。

定义GraphQL Controller

我么定义GraphQLController用来接收web请求的入参,示例如下:

@RestController@RequestMapping("graphql")public class GraphQLController {    private final GraphQL graphQL;    @Autowired    public GraphQLController(GraphQlSource graphQlSource) {        graphQL = graphQlSource.graphQl();    }    @PostMapping("query")    public ResponseEntity query(@RequestBody String query) {        ExecutionResult result = graphQL.execute(query);        return ResponseEntity.ok(result.getData());    }}

登录后复制

代码中GraphQL对象是执行查询的入口,但GraphQL只有一个私有的构造方法,所以不能直接注入,必须通过注入GraphQlSource的方式来获取GraphQL对象。

注意在GraphQL中我们只能使用String来接收参数,无法使用model对象,这是因为Graph请求参数并不是json结构。

测试Graph请求

我们创建一个graphql.http的文件,用于在idea中执行http请求

### Send POST request with json body
POST http://localhost:8080/graphql/query
Content-Type: application/json

{
  author(id: 1) {
    id
    firstName
    lastName
    birthdate
  }
}

### Send POST request with json body
POST http://localhost:8080/graphql/query
Content-Type: application/json

{
  allAuthors {
    id
    firstName
    lastName
    birthdate
  }
}

运行author(id: 1) 的查询,可以看到正常返回结果了。如果我们只需要 firstName和lastName两个字段,那么在请求入参中直接去掉id和birthdate就好了,而不用改动任何后端代码。

SpringBoot怎么使用GraphQL开发Web API

SpringBoot怎么使用GraphQL开发Web API

以上就是SpringBoot怎么使用GraphQL开发Web API的详细内容,更多请关注【创想鸟】其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。

发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2626769.html

(0)
上一篇 2025年3月7日 00:57:22
下一篇 2025年2月23日 13:45:22

AD推荐 黄金广告位招租... 更多推荐

相关推荐

发表回复

登录后才能评论