在sprint-boot中使用graphQL
簡介
graphQL介紹
略
spring-boot介紹
略
需求
我們以查詢書籍及其作者作為示例來展示graphql的使用
配置
- 新建maven工程,并添加spring-boot和graphql的依賴
<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>
<!-- https://mvnrepository.com/artifact/com.graphql-java/graphql-spring-boot-starter -->
<dependency>
<groupId>com.graphql-java</groupId>
<artifactId>graphql-spring-boot-starter</artifactId>
<version>3.10.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.graphql-java/graphql-java-tools -->
<dependency>
<groupId>com.graphql-java</groupId>
<artifactId>graphql-java-tools</artifactId>
<version>4.2.0</version>
</dependency>
- 定義數據類
定義Author類:
@Builder
@Data
public class Author {
private Integer id;
private String name;
private Integer age;
}
定義Book類:
@Builder
@Data
public class Book {
private Integer id;
private String name;
private Author author;
private String publisher;
}
- 添加QueryResolver
@Component
public class BookQueryResolver implements GraphQLQueryResolver {
public List<Book> findBooks() {
Author author = Author.builder()
.id(1)
.name("Bill Venners")
.age(40)
.build();
Book b = Book.builder()
.id(1)
.name("scala編程第三版")
.author(author)
.publisher("電子工業出版社")
.build();
List<Book> bookList = new ArrayList<Book>();
bookList.add(b);
return bookList;
}
}
在BookQueryResolver中我們添加了一個findeBooks方法,這里我們寫死了一個Book對象和一個Author對象,實現開發中根據自已的需要來獲取數據。
- 添加graphql的接口定義
在resources目錄添加root.graphqls和schema.graphqls文件。root.graphqls用于方法的定義,schema.graphqls用于定義可查詢數據及字段信息。
root.graphqls:
type Query {
findBooks: [Book]
}
schema.graphqls:
type Author {
id: Int
name: String
age: Int
}
type Book {
id: Int
name: String
author: Author
publisher: String
}
- 添加GraphqlApplication用于啟動我們的應用
@SpringBootApplication
public class GraphqlApplication {
public static void main(String [] args ) {
new SpringApplication(GraphqlApplication.class).run(args);
}
}
-
啟動程序
當我們在spring-boot的啟動日志里看到/graphql/*這樣的訪問路徑時,說明我們的graphql已經成功添加,如下圖所示
graphql.jpg - 添加圖形化工具
圖形化工具不是必需的,但是在我們的開發過程中,卻提供了很好的便利性,圖形工具的添加很簡單,在maven中添加如下依賴即可:
<dependency>
<groupId>com.graphql-java</groupId>
<artifactId>graphiql-spring-boot-starter</artifactId>
<version>3.10.0</version>
</dependency>
重新啟動應用,然后使用瀏覽器訪問http://localhost:8080/graphiql,如下圖:
graphiql.jpg
測試
-
我們調用findBooks查詢書名和出版社
graphql-1.jpg -
通過findBooks查詢書名和出版社的同時,查詢作者名稱
graphql-2.jpg
總結
示例很簡單,但graphql確實很好地解決了不同接口對查詢字段差異性的要求,而不會產生數據冗余,更多功能還待研究。
示例地址:示例