Spring Boot GraphQL 實戰系列,使用 Spring Boot 快速開發 GraphQL。
hello,大家好,我是小黑,又和大家見面啦~ 新開一個專題是關于 GraphQL 的相關内容,主要是通過 Spring Boot 來快速開發 GraphQL 應用,希望對剛接觸 GraphQL 的同學有所幫助。
先看一下官網的解釋:
https://graphql.org/ GraphQL is a query language for APIs and a runtime for fulfilling those queries with your existing data. GraphQL provides a complete and understandable description of the data in your API, gives clients the power to ask for exactly what they need and nothing more, makes it easier to evolve APIs over time, and enables powerful developer tools. https://graphql.cn/ GraphQL 既是一種用于 API 的查詢語言也是一個滿足你資料查詢的運作時。 GraphQL 對你的 API 中的資料提供了一套易于了解的完整描述,使得用戶端能夠準确地獲得它需要的資料,而且沒有任何備援,也讓 API 更容易地随着時間推移而演進,還能用于建構強大的開發者工具。
再看一下維基百科的解釋:
https://en.wikipedia.org/wiki/GraphQL GraphQL is an open-source data query and manipulation language for APIs, and a runtime for fulfilling queries with existing data.GraphQL was developed internally by Facebook in 2012 before being publicly released in 2015. It allows clients to define the structure of the data required, and the same structure of the data is returned from the server. GraphQL 是一種用于 api 的開源資料查詢和操作語言,也是一種用于實作現有資料查詢的運作時。GraphQL 于2012年由 Facebook内部開發,2015年公開釋出。 它允許用戶端定義所需資料的結構,并從伺服器傳回相同的資料結構。
從字面上了解:GraphQL = Graph + QL = 圖表化、可視化的查詢語言。它允許用戶端定義所需資料的結構,并從伺服器傳回相同的資料結構。
GraphQL 是一種規範,已有多種程式設計語言支援。
在本系列文章中,我們使用 graphql-spring-boot-starter 來完成 GraphQL 相關開發講解。
github 位址:https://github.com/graphql-java-kickstart/graphql-spring-boot
建構一個基礎的 Spring Boot Web 項目工程,引入最新的 graphql-spring-boot-starter:
通過 maven 我們可以很清楚的看到 graphql-spring-boot-starter 引入了哪些依賴包:

graphql-spring-boot-starter 預設情況下會掃描 classpath 下所有的 graphqls 字尾檔案。
當然,我們也可以通過 application.properties 來配置修改相關屬性,本案例中,我們使用預設配置即可。
在 resources 檔案夾下建立 schema.graphqls 檔案。
如果你在使用 idea 的話,可以安裝 https://plugins.jetbrains.com/plugin/8097-js-graphql 插件來幫助你編寫 graphqls 檔案。
上述 schema.graphqls 檔案中定義了 User 和 City 這兩種資料類型。同時,我們生成兩個 Java Bean 來與之相對應。
定義了一個 Spring Beran UserGraphQLQueryResolver ,實作了 graphql.kickstart.tools.GraphQLQueryResolver 接口
有一個名為 userList 的方法,方法不需要入參,傳回 Collection<User>
沒錯,聰明的讀者同學是不是已經發現了:
UserGraphQLQueryResolver#userList 就是用來比對 schema.graphqls 檔案中定義的擷取使用者清單查詢。
graphiql 可以幫助我們友善的向 graphql 服務端發起請求,使用也十分簡單,引入相關依賴即可。
好,讓我們啟動 Spring Boot 應用,通路 http://localhost:8080/graphiql
在 https://github.com/graphql-java-kickstart/graphql-spring-boot 的幫助下,實作一個 graphql 服務就是這麼的簡單。
我們來看看用戶端發出的請求長什麼樣子:
同時,我們可以通過 application.properties 檔案來修改服務端的請求接收路徑:
下面,我們再使用 GraphQL 的原生 api 來實作一下上述的案例。
下圖清晰的描述了上述程式中相關元件的關系: