在我的项目中,我需要从多个graphql端点获取数据。我在我的application.properties文件中定义了一个,如下所示:graphql.client.url=https://api.foo.com/graphql-1和在代码中获取数据:
public Foo getFooByid(String id) throws Exception {
final GraphQLRequest request =
GraphQLRequest.builder()
.query(orgByIdQuery)
.variables(Map.of("id", id))
.build();
final GraphQLResponse response = graphQLWebClient.post(request).block();
response.validateNoErrors();
return response.get("Foo", Foo.class);
}所以有一些魔法可以从application.properties文件中获取客户端url。现在,如何在代码中定义和使用第二个客户端url https://api.foo.com/graphql-2?gql的依赖关系:
<dependency>
<groupId>com.graphql-java-kickstart</groupId>
<artifactId>graphql-webclient-spring-boot-starter</artifactId>
<version>1.0.0</version>
</dependency>发布于 2022-10-27 10:37:11
一旦定义了所需的所有URL(将@值绑定到属性文件),您应该创建一个HttpGraphQlClient Bean,然后可以对每个请求进行变异:
@Bean
HttpGraphQlClient graphQlClient(){
return HttpGraphQlClient.builder()
.url(firstUrl)
.build();
}在你的另一个组件里你提出了你的第一个请求。
graphQlClient
.documentName(orgByIdQuery)
.retrieve("org")
... //etc然后,您可以任意修改它多次。
graphQlClient
.mutate()
.header("Authorization","Basic anVsaW86YHIJ0ZUJBMjAyMg==") //many different customizations are allowed
.url(anotherUrl)
.build()
.documentName(orgByIdQuery)
.retrieve("org")
... //etc希望能帮上忙!
发布于 2022-10-26 15:30:54
库似乎允许通过道具为一个客户端进行配置。其他客户端似乎必须以编程方式创建。
然后要么放在spring上下文中,要么在类内部使用。请参阅WebClientAutoConfiguration,它为生产的WebClient提供WebClient.Builder和自定义器。可以重用已经在spring上下文中的WebClient.Builder并设置另一个baseUrl,但是创建新的构建器并配置它似乎是更好的方法。可能的例子:
@Component
class GqlService(
objectMapper: ObjectMapper,
customizerProvider: ObjectProvider<WebClientCustomizer>,
@Value("\$graphql.client2.url") baseUrl: String
) {
private val secondGqlClient: GraphQLWebClient
init {
val builder = WebClient.builder()
customizerProvider.orderedStream().forEach { customizer -> customizer.customize(builder) }
builder.baseUrl(baseUrl)
secondGqlClient = GraphQLWebClient.newInstance(builder.build(), objectMapper)
}
}https://stackoverflow.com/questions/74210021
复制相似问题