SpringBoot開發秘籍之集成Graphql Query
概述
REST作為一種現代網絡應用非常流行的軟件架構風格受到廣大WEB開發者的喜愛,在目前軟件架構設計模式中隨處可見REST的身影,但是隨著REST的流行與發展,它的一個最大的缺點開始暴露出來:
在很多時候客戶端需要的數據往往在不同的地方具有相似性,但卻又不盡相同。
如同樣的用戶信息,在有的場景下前端只需要用戶的簡要信息(名稱、頭像),在其他場景下又需要用戶的詳細信息。當這樣的相似但又不同的地方多的時候,就需要開發更多的接口來滿足前端的需要。
隨著這樣的場景越來越多,接口越來越多,文檔越來越臃腫,前后端溝通成本呈指數增加。
基于上面的場景,我們迫切需要有一種解決方案或框架,可以使得在使用同一個領域模型(DO、DTO)的數據接口時可以由前端指定需要的接口字段,而后端根據前端的需求自動適配并返回對應的字段。
這就是我們今天的主角GraphQL。
場景模擬
考慮下面的場景:
用戶 與 文章 是一對多的關系,一個用戶可以發表多篇文章,同時又可以根據文章找到對應的作者。
我們需要構建以下幾個Graphql查詢:
- 根據用戶ID獲取用戶詳情,并獲取此用戶發表的所有文章
- 根據文章ID獲取文章詳情,并獲取文章作者的信息
當然項目是基于SpringBoot開發的。
開發實戰
在正式開發之前我推薦你在IDEA上安裝一下 JS GraphQL插件,這個插件方便我們編寫Schema,語法糾錯,代碼高亮等等。。。
創建一個SpringBoot項目
通過IDEA創建一個SpringBoot項目,并引入對應的jar
- <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>
- <!--graphql start-->
- <dependency>
- <groupId>com.graphql-java</groupId>
- <artifactId>graphql-spring-boot-starter</artifactId>
- <version>5.0.2</version>
- </dependency>
- <dependency>
- <groupId>com.graphql-java</groupId>
- <artifactId>graphql-java-tools</artifactId>
- <version>5.2.4</version>
- </dependency>
- <!--graphql end-->
- <dependency>
- <groupId>org.projectlombok</groupId>
- <artifactId>lombok</artifactId>
- </dependency>
- </dependencies>
這里主要需要引入 graphql-spring-boot-starter和 graphql-java-tools。
建立Java實體類
User
- @Data
- public class User {
- private int userId;
- private String userName;
- private String realName;
- private String email;
- private List<Post> posts;
- public User() {
- }
- public User(int userId, String userName, String realName, String email) {
- this.userId = userId;
- this.userName = userName;
- this.realName = realName;
- this.email = email;
- }
- }
Post
- @Data
- public class Post {
- private int postId;
- private String title ;
- private String text;
- private String category;
- private User user;
- public Post() {
- }
- public Post(int postId, String title, String text, String category) {
- this.postId = postId;
- this.title = title;
- this.text = text;
- this.category = category;
- }
- }
定義了兩個JAVA實體:Post,User。
編寫Schema文件
在resources/schema目錄下創建GraphQL Schema文件
- schema {
- query: Query,
- }
- type Query {
- # 獲取具體的用戶
- getUserById(id:Int) : User
- # 獲取具體的博客
- getPostById(id:Int) : Post
- }
- type User {
- userId : ID!,
- userName : String,
- realName : String,
- email : String,
- posts : [Post],
- }
- type Post {
- postId : ID!,
- title : String!,
- text : String,
- category: String
- user: User,
- }
如上,我們通過 type關鍵字定義了兩個對象,User與Post。在屬性后面添加!表明這是一個非空屬性,通過[Post]表明這是一個Post集合,類似于Java對象中List。
通過Query關鍵字定義了兩個查詢對象,getUserById,getPostById,分別返回User對象和Post對象。
關于schema的語法大家可以參考鏈接:https://graphql.org/learn/schema
編寫業務邏輯
PostService
- @Service
- public class PostService implements GraphQLQueryResolver {
- /**
- * 為了測試,只查詢id為1的結果
- */
- public Post getPostById(int id){
- if(id == 1){
- User user = new User(1,"javadaily","JAVA日知錄","zhangsan@qq.com");
- Post post = new Post(1,"Hello,Graphql","Graphql初體驗","日記");
- post.setUser(user);
- return post;
- }else{
- return null;
- }
- }
- }
UserService
- @Service
- public class UserService implements GraphQLQueryResolver {
- List<User> userList = Lists.newArrayList();
- public User getUserById(int id){
- return userList.stream().filter(item -> item.getUserId() == id).findAny().orElse(null);
- }
- @PostConstruct
- public void initUsers(){
- Post post1 = new Post(1,"Hello,Graphql1","Graphql初體驗1","日記");
- Post post2 = new Post(2,"Hello,Graphql2","Graphql初體驗2","日記");
- Post post3 = new Post(3,"Hello,Graphql3","Graphql初體驗3","日記");
- List<Post> posts = Lists.newArrayList(post1,post2,post3);
- User user1 = new User(1,"zhangsan","張三","zhangsan@qq.com");
- User user2 = new User(2,"lisi","李四","lisi@qq.com");
- user1.setPosts(posts);
- user2.setPosts(posts);
- userList.add(user1);
- userList.add(user2);
- }
- }
基于Graphql的查詢需要實現 GraphQLQueryResolver接口,由于為了便于演示我們并沒有引入數據層,請大家知悉。
配置Graphql 端點
- server.port = 8080
- graphql.servlet.corsEnabled=true
- # 配置端點
- graphql.servlet.mapping=/graphql
- graphql.servlet.enabled=true
配置完端口和端點后我們就可以對我們編寫的Graphql接口進行測試了。
接口地址為:localhost:8080/graphql
測試
這里我使用的是Chrome瀏覽器的 Altair Graphal Client插件,當然你還可以使用其他的客戶端工具,如:graphql-playground。
安裝插件
瀏覽器輸入chrome://extensions/,在擴展中心搜索Altair后即可添加至瀏覽器。
查詢
啟動SpringBoot項目,然后在打開的Altair插件界面,輸入Graphql端點 http://localhost:8080/graphql,然后點擊 Docs,將鼠標移至需要的查詢上,點擊 ADD QUERY 即可添加對應的查詢。
點擊Send Request 即可看到查詢結果:
然后我們在Query中可以根據我們的需要新增或刪除接口字段并重新請求接口,會看到響應結果中也會根據我們的請求自動返回結果:
小結
Graphql支持的數據操作有:
- 查詢(Query):獲取數據的基本查詢。
- 變更(Mutation):支持對數據的增刪改等操作。
- 訂閱(Subscription):用于監聽數據變動、并靠websocket等協議推送變動的消息給對方。
本節內容我們基于SpringBoot完成了Query的數據操作,實現過程還是相對比較簡單。希望此文能讓大家對Graphql有一個整體的了解,如果大家對Graphql感興趣后面還會更新此系列文章,完成對其他數據操作的整合。