本文介紹了在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
屬性創建相應的POJO類
這篇關于在Spring Boot中使用WebClient調用grapql突變API的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,