在此之前需要简单了解GraphQL的基本知识,可通过以下来源进行学习

GraphQL官方中文网站 :https://graphql.cn

GraphQL-java 官网:https://www.graphql-java.com

使用GraphQL需要

  定义对象模型

  定义查询类型

  定义查询操作 schema

#对应的User定义如下
schema { #定义查询
query: UserQuery
}
type UserQuery { #定义查询类型
user(): User #指定对象以及参数类型
}
type User { #定义对象
id: Long! #!表示非空
name:String
age:Int
}

java使用GraphQL需要引入GraphQL-java的依赖

        <!-- The dependence of graphql-java -->
<dependency>
<groupId>com.graphql-java</groupId>
<artifactId>graphql-java</artifactId>
<version>11.0</version>
</dependency>

对应的User

public class User {
private int age;
private long id;
private String name; public User(int age, long id, String name) {
this.age = age;
this.id = id;
this.name = name;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} public long getId() {
return id;
} public void setId(long id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
}
}

操作静态数据

import clc.bean.User;
import graphql.ExecutionResult;
import graphql.GraphQL;
import graphql.Scalars;
import graphql.schema.GraphQLFieldDefinition;
import graphql.schema.GraphQLObjectType;
import graphql.schema.GraphQLSchema;
import graphql.schema.StaticDataFetcher; /**
* ClassName: GraphQLDemo<br/>
* Description: <br/>
* date: 2019/6/28 10:40 AM<br/>
*
* @author chengluchao
* @since JDK 1.8
*/ public class GraphQLDemo {
public static void main(String[] args) {
//定义对象
GraphQLObjectType userObjectType = GraphQLObjectType.newObject()
.name("User")
.field(GraphQLFieldDefinition.newFieldDefinition().name("id").type(Scalars.GraphQLLong))
.field(GraphQLFieldDefinition.newFieldDefinition().name("age").type(Scalars.GraphQLInt))
.field(GraphQLFieldDefinition.newFieldDefinition().name("name").type(Scalars.GraphQLString))
.build();
//user : User 指定对象及参数类型
GraphQLFieldDefinition userFileldDefinition = GraphQLFieldDefinition.newFieldDefinition()
.name("user")
.type(userObjectType)
//静态数据
.dataFetcher(new StaticDataFetcher(new User(25, 2, "CLC")))
.build();
//type UserQuery 定义查询类型
GraphQLObjectType userQueryObjectType = GraphQLObjectType.newObject()
.name("UserQuery")
.field(userFileldDefinition)
.build();
//Schema 定义查询
GraphQLSchema qlSchema = GraphQLSchema.newSchema().query(userQueryObjectType).build(); GraphQL graphQL = GraphQL.newGraphQL(qlSchema).build();
String query = "{user{id,name,age}}";
ExecutionResult result = graphQL.execute(query);
System.out.println(result.toSpecification());
}
}

操作动态数据,数据源可以是数据库,缓存或者是其他服务,

此例通过动态传递id获取user数据,模拟实现动态数据

import clc.bean.User;
import graphql.ExecutionResult;
import graphql.GraphQL;
import graphql.Scalars;
import graphql.schema.GraphQLArgument;
import graphql.schema.GraphQLFieldDefinition;
import graphql.schema.GraphQLObjectType;
import graphql.schema.GraphQLSchema; /**
* ClassName: GraphQLDemo<br/>
* Description: <br/>
* date: 2019/6/28 10:40 AM<br/>
*
* @author chengluchao
* @since JDK 1.8
*/ public class GraphQLDemo2 {
public static void main(String[] args) {
//定义对象
GraphQLObjectType userObjectType = GraphQLObjectType.newObject()
.name("User")
.field(GraphQLFieldDefinition.newFieldDefinition().name("id").type(Scalars.GraphQLLong))
.field(GraphQLFieldDefinition.newFieldDefinition().name("age").type(Scalars.GraphQLInt))
.field(GraphQLFieldDefinition.newFieldDefinition().name("name").type(Scalars.GraphQLString))
.build();
//user : User 指定对象及参数类型
GraphQLFieldDefinition userFileldDefinition = GraphQLFieldDefinition.newFieldDefinition()
.name("user")
.type(userObjectType)
.argument(GraphQLArgument.newArgument().name("id").type(Scalars.GraphQLLong).build())
//动态数据
.dataFetcher(environment -> {
Long id = environment.getArgument("id");
//查库或者调用其他服务
return new User(20, id, "模拟用户1");
})
.build();
//type UserQuery 定义查询类型
GraphQLObjectType userQueryObjectType = GraphQLObjectType.newObject()
.name("UserQuery")
.field(userFileldDefinition)
.build();
//Schema 定义查询
GraphQLSchema qlSchema = GraphQLSchema.newSchema().query(userQueryObjectType).build(); GraphQL graphQL = GraphQL.newGraphQL(qlSchema).build();
String query = "{user(id:15){id,name,age}}";
ExecutionResult result = graphQL.execute(query);
System.out.println(result.toSpecification());
}
}

以上两个例子都是通过GraphQLObjectType的field等方法来定义模型,除此之外还可以通过SDL文件来生成模型

在resource目录下创建user.graphqls文件

#对应的User定义如下
schema { #定义查询
query: UserQuery
}
type UserQuery { #定义查询类型
user(id:Long) : User #指定对象以及参数类型
}
type User { #定义对象
id: Long! #!表示非空
name:String
age:Int
}

然后程序读取此文件即可解析成模型;

在此之前需要添加一个依赖包用于读取文件

     <dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>

详情如下:

  

import clc.bean.User;
import graphql.ExecutionResult;
import graphql.GraphQL;
import graphql.schema.GraphQLSchema;
import graphql.schema.idl.RuntimeWiring;
import graphql.schema.idl.SchemaGenerator;
import graphql.schema.idl.SchemaParser;
import graphql.schema.idl.TypeDefinitionRegistry;
import org.apache.commons.io.IOUtils; /**
* ClassName: GraphQLSDLDemo<br/>
* Description: <br/>
* date: 2019/6/28 11:19 AM<br/>
*
* @author chengluchao
* @since JDK 1.8
*/ public class GraphQLSDLDemo {
public static void main(String[] args) throws Exception {
//读取graphqls文件
String fileName = "user.graphqls";
String fileContent = IOUtils.toString(GraphQLSDLDemo.class.getClassLoader().getResource(fileName), "UTF-8");
//解析文件
TypeDefinitionRegistry typeDefinitionRegistry = new SchemaParser().parse(fileContent); RuntimeWiring wiring = RuntimeWiring.newRuntimeWiring()
.type("UserQuery", builder ->
builder.dataFetcher("user", environment -> {
Long id = environment.getArgument("id");
return new User(18, id, "user0" + id);
})
)
.build(); GraphQLSchema graphQLSchema = new SchemaGenerator().makeExecutableSchema(typeDefinitionRegistry, wiring); GraphQL graphQL = GraphQL.newGraphQL(graphQLSchema).build(); String query = "{user(id:15){id,name,age}}";
ExecutionResult result = graphQL.execute(query); System.out.println("query: " + query);
System.out.println(result.toSpecification());
}
}

官方推荐第二种方式

spring boot 使用GraphQL的更多相关文章

  1. 记录初学Spring boot中使用GraphQL编写API的几种方式

    Spring boot+graphql 一.使用graphql-java-tools方式 <dependency> <groupId>com.graphql-java-kick ...

  2. Spring Boot GraphQL 实战 01_快速入门

    hello,大家好,我是小黑,又和大家见面啦~ 新开一个专题是关于 GraphQL 的相关内容,主要是通过 Spring Boot 来快速开发 GraphQL 应用,希望对刚接触 GraphQL 的同 ...

  3. Spring Boot GraphQL 实战 02_增删改查和自定义标量

    hello,大叫好,我是小黑,又和大家见面啦~ 今天我们来继续学习 Spring Boot GraphQL 实战,我们使用的框架是 https://github.com/graphql-java-ki ...

  4. Spring Boot GraphQL 实战 03_分页、全局异常处理和异步加载

    hello,大家好,我是小黑,又和大家见面啦~ 今天我们来继续学习 Spring Boot GraphQL 实战,我们使用的框架是 https://github.com/graphql-java-ki ...

  5. 一个很有趣的示例Spring Boot项目,使用Giraphe CMS和Spring Boot

    6: 这是一个很有趣的示例Spring Boot项目,使用Giraphe CMS和Spring Boot. Giraphe是基于Spring Boot的CMS框架. https://github.co ...

  6. Spring Boot 集成 Swagger 生成 RESTful API 文档

    原文链接: Spring Boot 集成 Swagger 生成 RESTful API 文档 简介 Swagger 官网是这么描述它的:The Best APIs are Built with Swa ...

  7. 学习加密(四)spring boot 使用RSA+AES混合加密,前后端传递参数加解密

      学习加密(四)spring boot 使用RSA+AES混合加密,前后端传递参数加解密 技术标签: RSA  AES  RSA AES  混合加密  整合   前言:   为了提高安全性采用了RS ...

  8. Spring Boot 2.7.0发布,2.5停止维护,节奏太快了吧

    这几天是Spring版本日,很多Spring工件都发布了新版本, Spring Framework 6.0.0 发布了第 4 个里程碑版本,此版本包含所有针对 5.3.20 的修复补丁,以及特定于 6 ...

  9. Spring Boot 3.0.0 M3、2.7.0发布,2.5.x将停止维护

    昨晚(5月19日),Spring Boot官方发布了一系列Spring Boot的版本更新,其中包括: Spring Boot 3.0.0-M3 Spring Boot 2.7.0 Spring Bo ...

随机推荐

  1. D3.js的v5版本入门教程(第三章)—— 选择元素和绑定数据

    D3.js的v5版本入门教程(第三章) 在D3.js中,选择元素和绑定元素是最基本的内容,也是很重要的内容,等你看完整个教程后你会发现,这些D3.js教程都是在选择元素和绑定元素的基础上展开后续工作的 ...

  2. Intellij IDEA 智能补全的 10 个姿势,太牛逼了。。

    一年多前,栈长那时候刚从 Eclipse 转型 IDEA 成功,前面转了好多次,都是失败史,都是泪..后面我就在微信公众号 "Java技术栈" 写了这篇文章:Intellij ID ...

  3. linux学习(5):linux 性能瓶颈排查

    作为开发人员,肯定遇到过以下场景,应用突然卡住了,或者异常退出,cpu占用过高等各种异常情况,一般遇到这些异常情况,该如何去查找具体原因呢? linux和jdk提供了一些命令和工具来查看内存.cpu. ...

  4. go-micro框架学习1-准备工作

    下载golang环境,地址:https://studygolang.com/dl,这里使用的是1.11.10版本. 下载golang IDE,这里使用Lite,下载地址:http://liteide. ...

  5. 【NumPy】 之常见运算(np.around、np.floor、np.ceil、np.where)

    aroundnp.around 返回四舍五入后的值,可指定精度. around(a, decimals=0, out=None) a 输入数组 decimals 要舍入的小数位数. 默认值为0. 如果 ...

  6. WebGL学习笔记(四):绘图

    图元 WebGL可以绘制非常复杂的3D模型,这些模型都是由下面3种基本几何图元构成的,下面我们来详细的看看. 三角形 WebGL中任何复杂的模型,都是由三角形组合而成的,可以说三角形是任意形状的最小构 ...

  7. understand-show-slave-status-g

    https://dba.stackexchange.com/questions/22623/mysql-exec-master-log-pos-value-greater-than-read-mast ...

  8. [LeetCode] 244. Shortest Word Distance II 最短单词距离 II

    This is a follow up of Shortest Word Distance. The only difference is now you are given the list of ...

  9. SLA 99.99%以上!饿了么实时计算平台3年演进历程

    作者介绍 倪增光,饿了么BDI-大数据平台研发高级技术经理,曾先后就职于PPTV.唯品会.15年加入饿了么,组建数据架构team,整体负责离线平台.实时平台.平台工具的开发和运维,先后经历了唯品会.饿 ...

  10. SpringBoot系列教程web篇之如何自定义参数解析器

    title: 190831-SpringBoot系列教程web篇之如何自定义参数解析器 banner: /spring-blog/imgs/190831/logo.jpg tags: 请求参数 cat ...