在Spring Boot中使用WebClient调用grapql突变API
我在调用Spring Boot中的GraphQL突变API时卡住了。让我解释一下我的场景,我有两个微服务,一个是AuditConsumer服务,它使用来自active MQ的消息,另一个是GraphQL层,它只是从使用服务中获取数据并将其放入数据库中。当我尝试使用GraphQL游乐场或邮递员推送数据时,一切都很好。如何从AuditConsumer服务推送数据。在AuditConsumer eService中,我尝试将突变API作为字符串发送。负责将其发送到GraphQL层的方法是
public Mono<String> sendLogsToGraphQL(String logs){
return webClient
.post()
.uri("http://localhost:8080/logs/createEventLog")
.bodyValue(logs)
.retrieve()
.bodyToMono(String.class);
}
注意:我也尝试将数据作为对象传递,但没有用。
String logs
将从activeMQ分配给它。我发送的数据是;
{
"hasError": false,
"message": "Hello There",
"sender": "Ali Ahmad",
"payload": {
"type": "String",
"title": "Topoic",
"description": "This is the demo description of the activemqq"
},
"serviceInfo":{
"version": "v1",
"date": "2021-05-18T08:44:17.8237608+05:00",
"serverStatus": "UP",
"serviceName": "IdentityService"
}
}
突变将类似;
mutation($eventLog:EventLogInput){
createEventLog(eventLog: $eventLog){
hasError
message
payload{
title,
description
}
}
}
$eventLog
的正文为;
{
"eventLog": {
"hasError": false,
"message": "Hello There",
"sender": "Ali Ahmad",
"payload": {
"type": "String",
"title": "Topoic",
"description": "This is the demo description of the activemqq"
},
"serviceInfo":{
"version": "v1",
"date": "2021-05-18T08:44:17.8237608+05:00",
"serverStatus": "UP",
"serviceName": "IdentityService"
}
}
}
编辑 通过将Consumer服务更新为;,遵循以下答案。
@Component
public class Consumer {
@Autowired
private AuditService auditService;
private final String MUTATION_QUERY = "mutation($eventLog: EventLogInput){
" +
"createEventLog(eventLog: $eventLog){
" +
"hasError
" +
"}
" +
"}";
@JmsListener(destination = "Audit.queue")
public void consumeLogs(String logs) {
Gson gson = new Gson();
Object jsonObject = gson.fromJson(logs, Object.class);
Map<String, Object> graphQlBody = new HashMap<>();
graphQlBody.put("query", MUTATION_QUERY);
graphQlBody.put("variables", "{eventLog: " + jsonObject+ "}");
auditService.sendLogsToGraphQL(graphQlBody);
}
}
现在,`sendLogsToGraphQL‘将变为。
public void sendLogsToGraphQL(Map<String, String> logs) {
log.info("Logs: {} ", logs);
Mono<String> stringMono = webClient
.post()
.uri("http://localhost:8080/graphql")
.bodyValue(BodyInserters.fromValue(logs))
.retrieve()
.bodyToMono(String.class);
log.info("StringMono: {}", stringMono);
return stringMono;
}
数据未发送到具有指定URL的GraphQL层。
解决方案
您必须在POST请求中将query
和Body作为变量发送,如here
graphQlBody = { "query" : mutation_query, "variables" : { "eventLog" : event_log_json } }
然后在webClient中可以通过多种方式发送正文
public Mono<String> sendLogsToGraphQL(Map<String,Object> body){
return webClient
.post()
.uri("http://localhost:8080/logs/createEventLog")
.bodyValue(BodyInserters.fromValue(body))
.retrieve()
.bodyToMono(String.class);
}
这里我只展示了使用Map<String,Object>
来形成GraphQL请求体,但您也可以使用query
和variables
相关文章