Implementing request timeout in Rest API call

292 Views Asked by At

My rest microservice (spring boot) invokes a call on third party api service that may take long time to return hence I want to implement timeout so that the long running calls to this third party service does not cause app crashes. I have looked at various examples. Most say of using spring.mvc.async.request-timeout that can be set in properties file and the conroller end point returning callable. I am using cassandra DB and I noticed that when I run the test case to test the scenario , I get cassandra connection issue. When I remove the callable the JUnit test case runs but with no timeout.

Here is my controller end point and Junit test

@PostMapping("/deposit-accounts")
public Callable<ResponseEntity<DepositResponse>> 
getAccountCapabilities(@Valid @RequestBody DepositRequest request) {
           return () -> {
        final DepositResponse response = 
depositService.getCapabilities(request);
        if (response.getCapabilities().size() > 1 &&
                response.getCapabilities().stream()
                        .filter(c -> 
  ResponseCodes.INTERNAL_HOST_ERROR.equals(c.getResponseCode())).count() > 0) {
            return ResponseEntity.status(207).body(response);
        }
        return ResponseEntity.ok(response);
    };
}


@Test
@DisplayName("testResponseDelay")
void testResponseDelay() throws Exception
{
    String request = 
    readResourceFileToString("payloads/depositaccount/request.json");
    String casAPIResponse =
    readResourceFileToString
    ("payloads/depositaccount/cas/response.xml");
   
    mockCASApi.enqueue(new MockResponse()
    .setBody(casAPIResponse)
    .addHeader("Content-Type", TEXT_XML_VALUE));

    this.mockMvc
    .perform(post("/payments/capabilities/deposit")
    .contentType(MediaType.APPLICATION_JSON).content(request))
    .andExpect(status().is(200));
}

I am unable to figure out why callable causes the cassandra connection issue? Is above code right way of invoking callable?

For third party service invocation I use RestTemplate. Any pointers why the cassandra connection issue ? Is it related to using callable? is my usage of callable correct? Cassandra is run locally for Junit test.

The spring.mvc.async.request-timeout property is set in application yaml file.

mvc: async: request-timeout: 5000

My JUnit test case is as below:

thanks

0

There are 0 best solutions below