<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          Spring Boot + GraphQL 才是 API 的未來(lái)!

          共 10342字,需瀏覽 21分鐘

           ·

          2021-11-19 17:35

          相關(guān)閱讀:深圳一普通中學(xué)老師工資單曝光,秒殺程序員,網(wǎng)友:敢問是哪個(gè)學(xué)校畢業(yè)的?

          作者:NetWhite

          來(lái)源:blog.csdn.net/x763795151/article/details/117604505

          前言
          在淺嘗GraphQL一文描述了GraphQL及基本使用,本文提供一個(gè)基本示例,描述如何基于spring boot的web項(xiàng)目快速應(yīng)用。
          graphql-java的官方文檔:Getting started with GraphQL Java and Spring Boot,提供了相關(guān)依賴用以快速配置,但是個(gè)人真心不建議使用這個(gè)庫(kù)及相關(guān)配置方式來(lái)搭建腳手架,在實(shí)際開發(fā)中,業(yè)務(wù)比較復(fù)雜的時(shí)候,會(huì)導(dǎo)致需要配置的業(yè)務(wù)代碼比較多也比較繁瑣,相對(duì)下面這種方式,代碼復(fù)雜性比較高。
          本文提供一種更靈活快捷的方式,在spring boot項(xiàng)目中快速應(yīng)用開發(fā)。使用的依賴也和上面官方提供的都不一樣,請(qǐng)注意區(qū)分。

          快速開始

          創(chuàng)建spring boot工程

          通過(guò)Spring Initializr快速搭建,我選的jdk版本及spring boot版本,如下所示,其它版本未做兼容性測(cè)試。
          點(diǎn)擊下方的Generate按鈕:
          打開工程結(jié)構(gòu)如下,我將application.properties刪除了替換成applicaiton.yml,因?yàn)槲覀€(gè)人比較喜歡yaml的配置方式:搜索公眾號(hào)互聯(lián)網(wǎng)架構(gòu)師回復(fù)“2T”,送你一份驚喜禮包。

          引入相關(guān)依賴

          pom.xml配置如下:
          <?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
           <modelVersion>4.0.0</modelVersion>
           <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.4.6</version>
            <relativePath/> <!-- lookup parent from repository -->
           </parent>
           <groupId>com.xuxd</groupId>
           <artifactId>graphql.demo</artifactId>
           <version>0.0.1-SNAPSHOT</version>
           <name>graphql.demo</name>
           <description>GraphQL Demo project for Spring Boot</description>
           <properties>
            <java.version>1.8</java.version>
            <maven.compiler.source>1.8</maven.compiler.source>
            <maven.compiler.target>1.8</maven.compiler.target>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
            <lombok.version>1.18.20</lombok.version>
            <graphql-java-tools.version>11.0.1</graphql-java-tools.version>
            <gson.version>2.8.7</gson.version>
           </properties>
           <dependencies>
            <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter</artifactId>
            </dependency>

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

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

            <dependency>
             <groupId>org.projectlombok</groupId>
             <artifactId>lombok</artifactId>
             <version>${lombok.version}</version>
             <scope>provided</scope>
            </dependency>

            <dependency>
             <groupId>com.graphql-java-kickstart</groupId>
             <artifactId>graphql-java-tools</artifactId>
             <version>${graphql-java-tools.version}</version>
            </dependency>

            <dependency>
             <groupId>com.google.code.gson</groupId>
             <artifactId>gson</artifactId>
             <version>${gson.version}</version>
            </dependency>
           </dependencies>

           <build>
            <plugins>
             <plugin>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-maven-plugin</artifactId>
             </plugin>
            </plugins>
           </build>

          </project>

          初始化GraphQL實(shí)例

          我們將創(chuàng)建一個(gè)GraphQL實(shí)例并將其注冊(cè)到spring容器中,代碼如下。
          創(chuàng)建一個(gè)GraphQLProvider類:搜索公眾號(hào)互聯(lián)網(wǎng)架構(gòu)師回復(fù)“2T”,送你一份驚喜禮包。
          @Component
          public class GraphQLProvider {

              private GraphQL graphQL;

              @Autowired
              private IItemService itemService;

              @Bean
              public GraphQL graphQL() {
                  return graphQL;
              }

              @PostConstruct
              public void init() throws IOException {
                  GraphQLSchema graphQLSchema = SchemaParser.newParser()
                      .file("graphql/base.graphqls")
                      .resolvers(new Query(), new Mutation())
                      .file("graphql/item.graphqls")
                      .resolvers(new ItemResolver(itemService))
          //            .file("book.graphqls")
          //            .resolvers(new BookResolver())  //其它定義照上面的示例,繼續(xù)增加
                      .build().makeExecutableSchema();

                  this.graphQL = graphQL.newGraphQL(graphQLSchema).build();
              }

          }
          關(guān)于*.graphqls或者對(duì)應(yīng)的Resolver如ItemResolver,可以參看淺嘗GraphQL相關(guān)描述,這里只是作了微調(diào)整,相關(guān)代碼如下:
          base.grqphqls
          schema {
              # 查詢
              query: Query
              # 更新
              mutation: Mutation
          }

          type Query {
              version: String
          }

          type Mutation {
              version: String
          }
          item.graphqls
          # 定義一個(gè)查詢類型
          extend type Query {
              queryItemList: ItemList  # 定義查詢項(xiàng)目列表
              queryById(id: ID): Item
          }

          extend type Mutation {
              updateName(param: Param): Item
          }

          # 定義項(xiàng)目字段
          type Item {
              id: ID!
              code: String!
              name: String!
          }

          type ItemList {
              itemList: [Item!]!  #獲取項(xiàng)目列表
              total: Int!      # 獲取項(xiàng)目總數(shù)
          }

          input Param {
              id: ID!
              name: String!
          }
          ItemResolver
          public class ItemResolver implements GraphQLQueryResolver, GraphQLMutationResolver {

              private IItemService itemService;

              public ItemResolver(IItemService itemService) {
                  this.itemService = itemService;
              }

              // 對(duì)應(yīng)item.graphqls里的queryItemList
              public ItemList queryItemList() {
                  return itemService.queryItemList();
              }

              public Item queryById(Long id) {
                  return itemService.queryById(id);
              }

              public Item updateName(Param param) {
                  return itemService.updateName(param);
              }
          }
          相關(guān)業(yè)務(wù)代碼比較多,就不一一貼了。

          提供API

          我們需要暴露一個(gè)接口來(lái)接收請(qǐng)求,并作相關(guān)處理,也只需提供一個(gè)接口即可。因此我們創(chuàng)建一個(gè)Controller:GraphqlController.
          @RestController
          @RequestMapping("/graphql")
          @Log
          public class GraphqlController {

              @Autowired
              private GraphQL graphQL;

              @PostMapping
              public Object execute(@RequestBody GraphqlRequest request) {
                  ExecutionInput executionInput = ExecutionInput.newExecutionInput()
                      .query(request.getQuery())
                      .variables(request.getVariables())
                      .build();
                  Map<String, Object> result = new HashMap<>();

                  ExecutionResult executionResult = graphQL.execute(executionInput);
                  List<GraphQLError> errors = executionResult.getErrors();

                  if (errors != null && !errors.isEmpty()) {
                      result.put("errors", errors);
                      return result;
                  }
                  return executionResult.getData();
              }
          }
          到這一步,其實(shí)基本功能都已配置完成,可以啟動(dòng)項(xiàng)目進(jìn)行相關(guān)測(cè)試了。
          整個(gè)項(xiàng)目的代碼結(jié)構(gòu)如下,我盡量用了一個(gè)比較常規(guī)的web項(xiàng)目結(jié)構(gòu)(controller,service,dao等):搜索公眾號(hào)互聯(lián)網(wǎng)架構(gòu)師回復(fù)“2T”,送你一份驚喜禮包。

          測(cè)試

          示例中總共提供了3個(gè)接口,兩個(gè)查詢一個(gè)更新,分別進(jìn)行測(cè)試:
          ItemList queryItemList();

          Item queryById(Long id);

          Item updateName(Param param);
          查詢所有項(xiàng)目列表(只獲取每個(gè)項(xiàng)目的編碼和名稱,以及列表總數(shù)):
          根據(jù)ID查詢,獲取項(xiàng)目的id和名稱
          更新指定ID的項(xiàng)目名稱
          我們項(xiàng)目Id為1編碼為test的項(xiàng)目修改為“java項(xiàng)目”
          再查詢一下,可以看到結(jié)果更新了:

          結(jié)束語(yǔ)

          這樣整個(gè)項(xiàng)目的GraphQL相關(guān)的基本配置已經(jīng)完成,可以進(jìn)行業(yè)務(wù)開發(fā)了。

          1、985副教授工資曝光

          2、心態(tài)崩了!稅前2萬(wàn)4,到手1萬(wàn)4,年終獎(jiǎng)扣稅方式1月1日起施行~

          3、雷軍做程序員時(shí)寫的博客,很強(qiáng)大!

          4、人臉識(shí)別的時(shí)候,一定要穿上衣服啊!

          5、清華大學(xué):2021 元宇宙研究報(bào)告!

          6、績(jī)效被打3.25B,員工將支付寶告上了法院,判了

          瀏覽 24
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          評(píng)論
          圖片
          表情
          推薦
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  国产黄片在线播放 | 黄色污污污网站 | 99国产精品久久久久久久久久久 | 女人18片毛片60分钟黃菲菲 | 免费看A片秘 免费 |