Maven构建一个结合GraphQL服务的Spring Boot应用

本文使用Maven从零开始构建一个Spring Boot应用,以发布一个支持GraphQL的Web服务器。

1. 执行mvn archetype:generate

可以选择模板(但是已有的模板往往跟不上技术的进步),也可以只是生成一个基本的Maven项目。

2. 编辑生成的pom.xml文件,使之首先支持Spring Boot特性

    
        org.springframework.boot
        spring-boot-starter-parent
        2.0.1.RELEASE
    
    
        
            org.springframework.boot
            spring-boot-starter-web
        
    
    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    

3. 创建SpringBootApplication应用入口类

@SpringBootApplication
public class Eris4jApplication {
	public static void main(String[] args) {
		SpringApplication.run(GraphQLjApplication.class, args);
	}
}

4. 编辑pom.xml文件,使之支持GraphQL服务特性

        
            com.graphql-java
            graphql-spring-boot-starter
            4.0.0
        
        
            com.graphql-java
            graphiql-spring-boot-starter
            4.0.0
        

注意,graphql-spring-boot依赖于graphql-java。虽然目前graphql-java的最新版本是8.0,但是graphql-spring-boot 4.0.0项目不支持。如果结合graphql-java 8.0与graphql-spring-boot 4.0.0,将在启动GraphQL服务器时将抛出如下异常:

java.lang.ClassNotFoundException: graphql.execution.instrumentation.NoOpInstrumentation
原因是NoOpInstrumentation类只存在于graphql-java 7.0及以前版本,graphql-java 8.0中已经不存在了。

另外,graphql-spring-boot还依赖于graphql-java-servlet,以提供Web访问的URI endpoints,默认为http://localhost:8080/graphql/。,我们后续将介绍graphql-java-servlet。

注意,对graphiql-spring-boot-starter的依赖,使得我们测试可以访问http://localhost:8080/graphiql/

5. 定义可执行的GraphQLSchema对象,并使用@Bean将其标注为Spring bean

1) 可以直接创建GraphQLSchema对象,如下所示:

    @Bean
    GraphQLSchema schema() {
        String schema = "type Query {hello: String}";

        SchemaParser schemaParser = new SchemaParser();
        TypeDefinitionRegistry typeDefinitionRegistry = schemaParser.parse(schema);

        RuntimeWiring runtimeWiring = newRuntimeWiring()
                .type("Query", builder -> builder.dataFetcher("hello", new StaticDataFetcher("Xiangbin")))
                .build();

        SchemaGenerator schemaGenerator = new SchemaGenerator();
        return schemaGenerator.makeExecutableSchema(typeDefinitionRegistry, runtimeWiring);

2) 也可以使用graphql-java-tools,利用其中的GraphQLResolver和GraphQLScalar动态创建GraphQLSchema对象。

这时,graphql-java-tools将读取classpath下所有以*.graphqls为后缀名的文件,创建GraphQLSchema对象。具体*.graphqls文件的定义,请参考GraphQL规范。

6. 启动Spring Boot应用,使得GraphQL服务器就绪

启动Spring Boot应用的方法主要有两种,一种是在IDE中,执行run应用GraphQLApplication,另一种是在命令行中,执行java -jar target/myProjectName.jar。

GraphQL服务启动后,其URI默认为http://localhost:8080/graphql/,当然也可以在Spring Boot的application.properties配置文件中配置如下,改变其默认URI:

graphql.servlet.mapping=/mygraphql

7. 打开浏览器访问GraphQL服务

1) GET请求GraphQL服务器的Schema

http://localhost:8080/graphql/schema.json

2) POST请求查询具体的数据

http://localhost:8080/graphql
{"query":"{hello}"}


你可能感兴趣的:(Maven,Micro,Services,GraphQL,Spring,Boot,spring,boot,graphql,maven)