在此之前需要简单了解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. 【转】vue中样式被覆盖的问题,vue中的style不生效

    转载:http://www.cnblogs.com/shangjun6/p/11416054.html 在我们引入外部的样式时,发现自己无论如何都改不了外部的样式,自己的样式老被覆盖,究其原因还是我们 ...

  2. OpenTK学习笔记(1)-源码、官网地址

    OpenTK源码下载地址:https://github.com/opentk/opentk OpenTK使用Nuget安装命令:OpenTK:Install-Package OpenTK -Versi ...

  3. free中buffer 与 cache 的区别

    通常人们所说的Cache就是指缓存SRAM. SRAM叫静态内存,“静态”指的是当我们将一笔数据写入SRAM后,除非重新写入新数据或关闭电源,否则写入的数据保持不变. 由于CPU的速度比内存和硬盘的速 ...

  4. SQLServer replace函数

    declare @name char(1000) --注意:char(10)为10位,要是位数小了会让数据出错 set @name='ssssfcfgghdghdfcccs' select repla ...

  5. Wordpress 获取 custom post type 的当前文章 分类信息

    // knowledgebase_category 为 custom post type taxonomy $terms = get_the_terms( get_the_ID() , 'knowle ...

  6. typescript - 4.es5与typescript的类与继承

    ES5中的类与类的继承 (1)简单的类 function Person() { this.name = '张三'; this.age = 20; } var p = new Person(); ale ...

  7. Spring cloud微服务安全实战-7-11PinPoint+SpringBoot环境搭建

    微服务的最后一个组件, 调用链监控,一个请求进来以后,经过N多个微服务,例如a调用了b.b又调用了c,那么在这个过程中看到,整个的调用的链路,然后每一段调用所耗费的时间,帮你去分析你的系统如果出现瓶颈 ...

  8. Nginx 配置 HTTP 代理

    配置如下 #user nobody; worker_processes 1; #error_log logs/error.log; #error_log logs/error.log notice; ...

  9. 转 perl DBI 总结

    https://www.cnblogs.com/homezzm/archive/2011/07/22/2113618.html ##查看已经安装的包 #!/usr/bin/perluse strict ...

  10. 嵌入式LINUX基础教程 第2版

    嵌入式LINUX基础教程  第2版 目录 第1章 入门 11.1 为什么选择Linux 11.2 嵌入式Linux现状 21.3 开源和GPL 21.4 标准及相关组织 31.4.1 Linux标准基 ...