簡體   English   中英

使用 webclient 在 spring 啟動中調用 grapql 突變 API

[英]using webclient to call the grapql mutation API in spring boot

我在 spring 引導中調用 graphQL 突變 API 時卡住了。 讓我解釋一下我的場景,我有兩個微服務,一個是 AuditConsumeService,它使用來自 activeMQ 的消息,另一個是 GraphQL 層,它只是從消費服務中獲取數據並將其放入數據庫中。 當我嘗試使用 graphql 游樂場或 postman 推送數據時,一切都很好。 如何從 AuditConsumeService 推送數據。 在 AuditConsumeService 中,我試圖將突變 API 作為字符串發送。 負責將其發送到 graphQL 層的方法是

public Mono<String> sendLogsToGraphQL(String logs){
        return webClient
                .post()
                .uri("http://localhost:8080/logs/createEventLog")
                .bodyValue(logs)
                .retrieve()
                .bodyToMono(String.class);
    }  

注意:我也嘗試將數據作為 Object 傳遞,但沒有用。 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的主體為 json;

{
  "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"
    }
}
}

您必須在發布請求中將query和正文作為變量發送,如下所示

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 請求體,但您也可以使用queryvariables的屬性創建相應的 POJO 類

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM