Search code examples
springspring-bootreactive-programmingspring-webfluxspring-web

Spring boot 2 WebClient get context parameter in subscriber


I am using WebClient to call an external API, I am associating a requestId for each request. Once the request is processed and response is received, I am updating some table using the requestId so that I can confirm all the data associated with the requestId are processed.

public void getEmployeeData(List<Integer>employeeIds, String requestId){
   WebClient webClient = WebClient.builder().baseUrl(baseUrl).build();

   webClient.post().uri(uri)
            .contentType(MediaType.APPLICATION_JSON_UTF8)
            .accept(MediaType.APPLICATION_JSON_UTF8)
            .header(HttpHeaders.AUTHORIZATION, "Basic " + Base64Utils
            .encodeToString((plainCreds)
            .getBytes(Charset.defaultCharset())))
            .body(BodyInserters.fromObject(body)).retrieve()
            .bodyToFlux(EmployeeInfo.class)
            .doOnError(throwable -> {
               Mono.error(throwable);
            }).subscribe(new Consumer<EmployeeInfo>() {
                @Override
                public void accept(EmployeeInfo employeeInfo) {
                    // Here I need the requestId which is passed as function 
                    //parameter
              }
            }); 
}

The above function receives list of employee Ids with a requestid, i have to call external API to get the Information for the list of employees, before calling this function i am saving all the list of employees against the requestid, so that once the response is received I can update the table stating that all the employee info is received for given requestId. Now in the subscriber part i need the requestId so that I can correlate that the response received belongs to a particular requestid


Solution

  • You may add final on requestId so that it's usable on your subscribe function.

    public void getEmployeeData(List<Integer>employeeIds, final String requestId){