GraphQL实战-第二篇-java实现及分析
到这里必须具备的知识储备:对GraphQL有简单的了解,了解Schema的常用类型。
这里用一些demo示例来体验GraphQL的执行过程,这只是借助graphql-java实现的java版本。
首先需要引入graphql-java的依赖
<dependency>
<groupId>com.graphql-java</groupId>
<artifactId>graphql-java</artifactId>
<version>15.0</version>
</dependency>
Demo1
第一个demo是官网提供的
import graphql.ExecutionResult;
import graphql.GraphQL;
import graphql.schema.GraphQLSchema;
import graphql.schema.StaticDataFetcher;
import graphql.schema.idl.RuntimeWiring;
import graphql.schema.idl.SchemaGenerator;
import graphql.schema.idl.SchemaParser;
import graphql.schema.idl.TypeDefinitionRegistry;
import static graphql.schema.idl.RuntimeWiring.newRuntimeWiring;
public class HelloWorld {
public static void main(String[] args) {
//定义schema文件,直接写在了代码中,包含一个hello的查询方法
String schema = "type Query{hello: String} schema{query: Query}";
SchemaParser schemaParser = new SchemaParser();
//直接加载schema,初始化GraphQL
TypeDefinitionRegistry typeDefinitionRegistry = schemaParser.parse(schema);
//加载一份服务端数据
RuntimeWiring runtimeWiring = new RuntimeWiring()
.type("Query", builder -> builder.dataFetcher("hello", new StaticDataFetcher("world")))
.build();
SchemaGenerator schemaGenerator = new SchemaGenerator();
GraphQLSchema graphQLSchema = schemaGenerator.makeExecutableSchema(typeDefinitionRegistry, runtimeWiring);
// 构建一个GraphQL实例,执行graphql脚本
GraphQL build = GraphQL.newGraphQL(graphQLSchema).build();

本文通过几个实战示例介绍如何使用GraphQL-java库构建GraphQL服务,包括加载schema、处理请求参数和响应数据。
最低0.47元/天 解锁文章
601

被折叠的 条评论
为什么被折叠?



