合并多个 GraphQL 模式
在 Spring Boot 环境中实现模式拼接,组合并公开多个 GraphQL 服务。
合并多个 GraphQL 模式 是 CoddyKit 上的免费 GraphQL APIs with Spring Boot 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 GraphQL APIs with Spring Boot 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 GraphQL APIs with Spring Boot 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Unifying Your GraphQL APIs
As your application grows, you might find yourself with multiple independent GraphQL services. How do you present them as a single, cohesive API to your clients?
This lesson will guide you through implementing schema stitching in a Spring Boot application. You'll learn to combine multiple backend GraphQL schemas into one unified endpoint.
Acting as a Gateway
A GraphQL Gateway acts as a central entry point for all your client applications. Instead of clients querying multiple services directly, they query the gateway.
- The gateway knows about all backend GraphQL services.
- It fetches their individual schemas.
- It combines these schemas into a single, unified schema.
- It then routes incoming client queries to the correct backend service and aggregates the results.
Setting Up Your Spring Boot Gateway
Let's start by creating a new Spring Boot project. We'll need a few key dependencies to build our gateway:
spring-boot-starter-web: For web capabilities.spring-graphql: To serve our combined GraphQL API.graphql-java: The core library for building and manipulating GraphQL schemas.
Add these to your pom.xml or build.gradle.
Pointing to Backend Services
Our gateway needs to know where the backend GraphQL services are located. We can configure their URLs, perhaps in application.properties or through a dedicated configuration class.
For example, imagine we have a UserService and a ProductService, each with its own GraphQL endpoint:
application.properties:
graphql.remote-services.user-service.url=http://localhost:8081/graphql
graphql.remote-services.product-service.url=http://localhost:8082/graphqlIn a real application, these would be separate Spring Boot applications.
Fetching Remote Schemas via Introspection
Before we can combine schemas, our gateway needs to discover what fields and types each backend service offers. This is done using introspection.
GraphQL provides a special introspection query that allows you to ask a GraphQL server for information about its schema. The gateway will send this query to each backend service to get their Schema Definition Language (SDL).
Fetching Schema Definition Language
Here's a simple Spring Boot component that uses WebClient to perform an introspection query and retrieve the SDL from a remote GraphQL service. This SDL will later be used to build our combined schema.
package com.coddykit.gateway;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
@Component
public class RemoteSchemaFetcher {
private final WebClient webClient;
public RemoteSchemaFetcher(WebClient.Builder webClientBuilder) {
this.webClient = webClientBuilder.baseUrl("").build();
}
// Simplified introspection query for demo
private static final String INTROSPECTION_QUERY_BODY =
"{\"query\":\"query { __schema { queryType { name } } }\"}";
public Mono<String> fetchSchemaSdl(String serviceUrl) {
return webClient.post()
.uri(serviceUrl)
.bodyValue(INTROSPECTION_QUERY_BODY)
.retrieve()
.bodyToMono(String.class)
.map(response -> {
// In a real app, you'd parse the 'response' JSON
// to extract the actual SDL. For this example,
// we'll return a basic placeholder SDL.
return "type Query { userCount: Int }"; // Example SDL from a remote service
});
}
public static void main(String[] args) {
// This main method is for illustrative purposes only.
// In a real Spring Boot app, this component would be managed by Spring.
System.out.println("RemoteSchemaFetcher component simulates fetching SDL.");
System.out.println("It uses WebClient to send an introspection query.");
System.out.println("Actual parsing of the introspection result is omitted for brevity.");
}
}Combining Schema Definitions
Once we have the SDL strings from all our backend services, we need to combine them into a single GraphQLSchema object. The graphql-java library provides tools for this.
- Use
SchemaParserto parse each SDL string into aTypeDefinitionRegistry. - Merge these
TypeDefinitionRegistryobjects. - Use
SchemaGeneratorwith the merged registry to create the final unifiedGraphQLSchema.
This combined schema is what your gateway will expose to clients.
Merging Type Definition Registries
This example demonstrates how to combine two TypeDefinitionRegistry objects into one. This is the core step in building our unified schema.
package com.coddykit.gateway;
import graphql.schema.GraphQLSchema;
import graphql.schema.idl.SchemaGenerator;
import graphql.schema.idl.SchemaParser;
import graphql.schema.idl.TypeDefinitionRegistry;
public class SchemaCombiner {
public GraphQLSchema combineSchemas(String userSchemaSdl, String productSchemaSdl) {
SchemaParser schemaParser = new SchemaParser();
// Parse individual SDLs into TypeDefinitionRegistry
TypeDefinitionRegistry userRegistry = schemaParser.parse(userSchemaSdl);
TypeDefinitionRegistry productRegistry = schemaParser.parse(productSchemaSdl);
// Merge the registries
TypeDefinitionRegistry mergedRegistry = new TypeDefinitionRegistry();
mergedRegistry.merge(userRegistry);
mergedRegistry.merge(productRegistry);
// Generate the final GraphQLSchema
SchemaGenerator schemaGenerator = new SchemaGenerator();
return schemaGenerator.makeExecutableSchema(mergedRegistry);
}
public static void main(String[] args) {
String userSdl = "type Query { user(id: ID!): User } type User { id: ID! name: String }";
String productSdl = "type Query { product(id: ID!): Product } type Product { id: ID! name: String price: Float }";
SchemaCombiner combiner = new SchemaCombiner();
GraphQLSchema combinedSchema = combiner.combineSchemas(userSdl, productSdl);
System.out.println("Combined Schema Generated Successfully!");
// You can inspect combinedSchema.getTypeMap() to see merged types
System.out.println("Query types in merged schema: " +
combinedSchema.getQueryType().getFieldDefinitions().size());
System.out.println("Expected 2 query fields (user, product).");
}
}Routing Queries with DataFetchers
After combining schemas, when a client queries the gateway, the gateway needs to know which backend service should handle each field.
This is achieved using a Delegating DataFetcher. For each field in the stitched schema, this DataFetcher will:
- Identify the original backend service for that field.
- Construct a sub-query for that backend.
- Send the sub-query to the correct backend service.
- Receive the response and integrate it into the overall result.
This is the "runtime" part of stitching, where data is actually fetched.
Stitching Knowledge Check
You've learned about the key steps involved in merging multiple GraphQL schemas in a Spring Boot gateway. Which of the following is the PRIMARY reason for using a Delegating DataFetcher in a stitched GraphQL gateway?
Recap: Building a Unified API
Congratulations! You've learned the fundamental steps to merge multiple GraphQL schemas using Spring Boot:
- Setup a Spring Boot gateway with necessary dependencies.
- Configure remote backend GraphQL service URLs.
- Introspect each remote service to fetch its Schema Definition Language (SDL).
- Combine the SDLs into a single
GraphQLSchemausinggraphql-java. - Implement
Delegating DataFetchersto route client queries to the appropriate backend service at runtime.
This unified approach simplifies client interactions and provides a consistent API experience.
用 AI 导师学习 GraphQL APIs with Spring Boot — 免费
在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。
- 课程
- 12
- 课程
- 48
常见问题解答
「合并多个 GraphQL 模式」课时是免费的吗?
是的 — 「合并多个 GraphQL 模式」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 GraphQL APIs with Spring Boot 课程的其余内容,请升级到 CoddyKit PRO。 GraphQL APIs with Spring Boot 课程共包含 4 节课。
「合并多个 GraphQL 模式」这节课中我会学到什么?
在 Spring Boot 环境中实现模式拼接,组合并公开多个 GraphQL 服务。 你通过在浏览器中直接运行的动手代码来练习 GraphQL APIs with Spring Boot,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 GraphQL APIs with Spring Boot 需要有经验吗?
无需任何先前经验。CoddyKit 上的 GraphQL APIs with Spring Boot 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。
「合并多个 GraphQL 模式」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 GraphQL APIs with Spring Boot 课中编写并运行代码吗?
能。每节 GraphQL APIs with Spring Boot 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 构建自定义指令
- 模式拼接基础
- 合并多个 GraphQL 模式
- 使用类型扩展实现模式模块化