跳到主要内容
版本:7.0.2

GraphQL 支持

DeepSeek V3 中英对照 GraphQL Support

Spring Integration 提供了用于与 GraphQL 协议交互的通道适配器。该实现基于 Spring for GraphQL

此依赖项为项目所需:

<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-graphql</artifactId>
<version>7.0.2</version>
</dependency>

GraphQL 出站网关

GraphQlMessageHandler 是一个 AbstractReplyProducingMessageHandler 扩展,代表一个出站网关契约,用于执行 GraphQL querymutationsubscription 操作并生成其结果。它需要一个 org.springframework.graphql.ExecutionGraphQlService 来执行 operation,该服务可以静态配置或通过针对请求消息的 SpEL 表达式进行配置。operationName 是可选的,同样可以静态配置或通过 SpEL 表达式配置。variablesExpression 也是可选的,用于参数化操作。locale 是可选的,用于 GraphQL Java 库中的操作执行上下文。executionId 可以通过 SpEL 表达式配置,默认为请求消息的 id 头部。

如果请求消息的有效载荷是 ExecutionGraphQlRequest 的实例,那么在 GraphQlMessageHandler 中不会执行任何设置操作,并且此类输入将直接用于 ExecutionGraphQlService.execute()。否则,将使用上述提到的 SpEL 表达式,根据请求消息确定 operationoperationNamevariablesexecutionId

GraphQlMessageHandler 是一个响应式流组件,它通过执行 ExecutionGraphQlService.execute(ExecutionGraphQlRequest) 生成一个 Mono<ExecutionGraphQlResponse> 作为回复。当输出通道不是响应式时,框架会在 ReactiveStreamsSubscribableChannel 输出通道或 AbstractMessageProducingHandler 中异步订阅这个 Mono。关于如何处理 GraphQL 操作结果,请参阅 ExecutionGraphQlResponse 的文档。

@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,必须手动订阅并处理。或者,可以通过普通的服务激活器将其扁平映射到 FluxMessageChannel 的回复中:

@ServiceActivator(inputChannel = "graphQlResultChannel", outputChannel="graphQlSubscriptionChannel")
public SubscriptionPublisher obtainSubscriptionResult(ExecutionGraphQlResponse graphQlResponse) {
return graphQlResponse.getData();
}

这样的出站网关不仅可用于通过HTTP发送GraphQL请求,还可用于处理任何在消息中生成或携带GraphQL操作及其参数的上游端点。GraphQlMessageHandler的处理结果可以作为对上游请求的回复生成,也可以发送到下游以在集成流中进行进一步处理。