spring boot 使用GraphQL

在此之前需要简单了解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的依赖

        
        <dependency>
            <groupId>com.graphql-javagroupId>
            <artifactId>graphql-javaartifactId>
            <version>11.0version>
        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
* Description:
* date: 2019/6/28 10:40 AM
* *
@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
* Description:
* date: 2019/6/28 10:40 AM
* *
@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-iogroupId>
            <artifactId>commons-ioartifactId>
            <version>2.6version>
        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
* Description:
* date: 2019/6/28 11:19 AM
* *
@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)