温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

SpringBoot怎么使用GraphQL开发Web API

发布时间:2023-04-04 13:36:28 来源:亿速云 阅读:116 作者:iii 栏目:开发技术

这篇文章主要讲解了“SpringBoot怎么使用GraphQL开发Web API”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“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,则可以添加以下依赖项

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-graphql</artifactId>
        </dependency>

定义 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层,它是实现基础数据的核心。

以下是一个简单示例:

@Component
public 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<Object> 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”的内容了,经过本文的学习后,相信大家对SpringBoot怎么使用GraphQL开发Web API这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI