|
如需使用最新稳定版本,请使用 Spring Integration 7.0.4! |
GraphQL 支持
Spring Integration 提供了用于与 GraphQL 协议交互的信道适配器。 该实现基于 Spring for GraphQL。
您需要将以下依赖项包含到您的项目中:
-
Maven
-
Gradle
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-graphql</artifactId>
<version>6.4.10</version>
</dependency>
compile "org.springframework.integration:spring-integration-graphql:6.4.10"
GraphQL 出站网关
The GraphQlMessageHandler 是一个 AbstractReplyProducingMessageHandler 扩展,用于表示执行 GraphQL query、mutation 或 subscription 操作并返回其结果的外部网关契约。
它需要一个 org.springframework.graphql.ExecutionGraphQlService 来执行 operation,该配置可以是静态的,也可以通过对请求消息使用 SpEL 表达式进行配置。
operationName 是可选的,同样支持静态配置或通过 SpEL 表达式配置。
variablesExpression 也是可选的,用于参数化操作。
locale 是可选的,用于在 GraphQL Java 库中设置操作执行上下文。
executionId 可通过 SpEL 表达式进行配置,默认值为请求消息的 id 头部。
如果请求消息的负载是 ExecutionGraphQlRequest 的实例,那么在 GraphQlMessageHandler 中不会执行任何设置操作,并且该输入将按原样用于 ExecutionGraphQlService.execute()。
否则,将根据上述 SpEL 表达式确定 operation、operationName、variables 和 executionId。
GraphQlMessageHandler 是一个响应式流组件,并在 ExecutionGraphQlService.execute(ExecutionGraphQlRequest) 之后产生 Mono<ExecutionGraphQlResponse> 作为结果。
框架会在 ReactiveStreamsSubscribableChannel 输出通道中订阅此类 Mono,或者在输出通道非响应式时于 AbstractMessageProducingHandler 中异步订阅。
请查阅关于 ExecutionGraphQlResponse 的文档以了解如何处理 GraphQL 操作结果。
@Bean
GraphQlMessageHandlerSpec graphQlMessageHandlerSpec(ExecutionGraphQlService graphQlService) {
return GraphQl.gateway(graphQlService)
.operation("""
query HeroNameAndFriends($episode: Episode) {
hero(episode: $episode) {
name
friends {
name
}
}
}""")
.variablesExpression("{episode:'JEDI'}");
}
@Bean
IntegrationFlow graphqlQueryMessageHandlerFlow(GraphQlMessageHandler handler) {
return IntegrationFlow.from(MessageChannels.flux("inputChannel"))
.handle(handler)
.channel(c -> c.flux("resultChannel"))
.get();
}
@Bean
ExecutionGraphQlService graphQlService(GraphQlSource graphQlSource) {
return new DefaultExecutionGraphQlService(graphQlSource);
}
@Bean
GraphQlSource graphQlSource(AnnotatedControllerConfigurer annotatedDataFetcherConfigurer) {
return GraphQlSource.builder()
.schemaResources(new ClassPathResource("graphql/test-schema.graphqls"))
.configureRuntimeWiring(annotatedDataFetcherConfigurer)
.build();
}
@Bean
AnnotatedControllerConfigurer annotatedDataFetcherConfigurer() {
return new AnnotatedControllerConfigurer();
}
对于订阅操作的结果应进行特殊处理。
在这种情况下,ExecutionGraphQlResponse.getData() 返回一个需要手动订阅和处理的 SubscriptionPublisher。
或者,它可以通过普通的 Service Activator 平映射到 FluxMessageChannel 的回复:
@ServiceActivator(inputChannel = "graphQlResultChannel", outputChannel="graphQlSubscriptionChannel")
public SubscriptionPublisher obtainSubscriptionResult(ExecutionGraphQlResponse graphQlResponse) {
return graphQlResponse.getData();
}
此类出站网关不仅可用于通过 HTTP 发送 GraphQL 请求,还可用于任何上游端点,该端点在消息中生成或承载 GraphQL 操作或其参数。
GraphQlMessageHandler 处理的结果可以作为对上游请求的响应返回,或发送至下游以在集成流中进行进一步处理。