• 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的依赖

            <!-- 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());
        }
    }

    官方推荐第二种方式

  • 相关阅读:
    记一次lvs-tunnel模式的故障分析(7)
    Zabbix实战-简易教程(4)--Server端安装
    Zabbix实战-简易教程(3)--DB安装和表分区
    HDFS跨外部存储系统的多层级存储
    HDFS副本放置节点选择的优化
    HDFS副本放置节点选择的优化
    HDFS的新方向:Ozone对象存储
    HDFS的新方向:Ozone对象存储
    聊聊HDFS中的副本放置策略和磁盘选择策略间的选择“矛盾”
    聊聊HDFS中的副本放置策略和磁盘选择策略间的选择“矛盾”
  • 原文地址:https://www.cnblogs.com/chenglc/p/11103269.html
Copyright © 2020-2023  润新知