SpringBoot 开发秘籍 - 集成 Graphql Query - 今日头条

本文由 简悦 SimpRead 转码, 原文地址 www.toutiao.com

用户 与 文章 是一对多的关系,一个用户可以发表多篇文章,同时又可以根据文章找到对应的作者。在正式开发之前我推荐你在 IDEA 上安装一下 JS G

REST 作为一种现代网络应用非常流行的软件架构风格受到广大 WEB 开发者的喜爱,在目前软件架构设计模式中随处可见 REST 的身影,但是随着 REST 的流行与发展,它的一个最大的缺点开始暴露出来:

在很多时候客户端需要的数据往往在不同的地方具有相似性,但却又不尽相同。

如同样的用户信息,在有的场景下前端只需要用户的简要信息(名称、头像),在其他场景下又需要用户的详细信息。当这样的相似但又不同的地方多的时候,就需要开发更多的接口来满足前端的需要。

随着这样的场景越来越多,接口越来越多,文档越来越臃肿,前后端沟通成本呈指数增加。

基于上面的场景,我们迫切需要有一种解决方案或框架,可以使得在使用同一个领域模型(DO、DTO)的数据接口时可以由前端指定需要的接口字段,而后端根据前端的需求自动适配并返回对应的字段。

这就是我们今天的主角 GraphQL

考虑下面的场景:

https://p26.toutiaoimg.com/origin/pgc-image/ffe5b16dc3bb4edb9c1331132a7de668?from=pc

用户 与 文章 是一对多的关系,一个用户可以发表多篇文章,同时又可以根据文章找到对应的作者。

我们需要构建以下几个 Graphql 查询:

  • 根据用户 ID 获取用户详情,并获取此用户发表的所有文章
  • 根据文章 ID 获取文章详情,并获取文章作者的信息

当然项目是基于 SpringBoot 开发的。

在正式开发之前我推荐你在 IDEA 上安装一下 JS GraphQL 插件,这个插件方便我们编写 Schema,语法纠错,代码高亮等等。。。

https://p26.toutiaoimg.com/origin/pgc-image/55dc68ab6b42455eb0c3e1cb3bb9fc28?from=pc

通过 IDEA 创建一个 SpringBoot 项目,并引入对应的 jar

xml

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<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。

User

java

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
@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

java

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
@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。

在 resources/schema 目录下创建 GraphQL Schema 文件

go

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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

java

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
@Service
public class PostService implements GraphQLQueryResolver {
    /**
     * 为了测试,只查询id为1的结果
     */
    public Post getPostById(int id){
        if(id == 1){
            User user = new User(1,"javadaily","JAVA日知录","[email protected]");
            Post post = new Post(1,"Hello,Graphql","Graphql初体验","日记");
            post.setUser(user);
            return post;
        }else{
            return null;
        }

    }
}

UserService

java

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
@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","张三","[email protected]");
        User user2 = new User(2,"lisi","李四","[email protected]");

        user1.setPosts(posts);
        user2.setPosts(posts);


        userList.add(user1);
        userList.add(user2);

    }

}

基于 Graphql 的查询需要实现 GraphQLQueryResolver 接口,由于为了便于演示我们并没有引入数据层,请大家知悉。

1
2
3
4
5
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 后即可添加至浏览器。

https://p26.toutiaoimg.com/origin/pgc-image/f5def0a2a09344e4a8ed3b29aa9d6b45?from=pc

启动 SpringBoot 项目,然后在打开的 Altair 插件界面,输入 Graphql 端点 http://localhost:8080/graphql,然后点击 Docs,将鼠标移至需要的查询上,点击 ADD QUERY 即可添加对应的查询。

https://p26.toutiaoimg.com/origin/pgc-image/c86796abe104477cb1b0c9124db61e70?from=pc

点击 Send Request 即可看到查询结果:

https://p26.toutiaoimg.com/origin/pgc-image/cb90c5421a534871ab69d18f1995fba9?from=pc

然后我们在 Query 中可以根据我们的需要新增或删除接口字段并重新请求接口,会看到响应结果中也会根据我们的请求自动返回结果:

https://p26.toutiaoimg.com/origin/pgc-image/a87d78cfc2c9489c87df163301c071d6?from=pc

Graphql 支持的数据操作有:

  • 查询(Query) :获取数据的基本查询。
  • 变更(Mutation) :支持对数据的增删改等操作。
  • 订阅(Subscription) :用于监听数据变动、并靠 websocket 等协议推送变动的消息给对方。

https://p26.toutiaoimg.com/origin/pgc-image/e6dc7315461d47d9ae88e5dc39b03eba?from=pc

本节内容我们基于 SpringBoot 完成了 Query 的数据操作,实现过程还是相对比较简单。希望此文能让大家对 Graphql 有一个整体的了解,如果大家对 Graphql 感兴趣后面还会更新此系列文章,完成对其他数据操作的整合。