I have an API endpoint /api1
that will make 2 service calls -
- insertIndb(), called on certain inputs
- verify(), called on certain inputs
I want to return the response of insertIndb()
to the caller when they call /api1
only and not the verify()
call. The verify()
call if called, the caller need not wait for the response of this call but just get something like response in process
. Since the goal of verify()
is to update db and not return back anything.
So I was suggested to make this verify
call in background. How can I do that?
Summarizing my flow below:
- Enduser send POST
/api1
with payload entity. - If entity does not exist,
- the
/api1
will make ainsertIndb()
call and return the response to the end user as 200. - After this, It will call
/verify
in background, the enduser need not wait for the response. // How to do this?
- the
- If entity exists,
- It will only call
/verify
in background, the enduser need not wait for the response. // How to do this? - Probably return just 200 on your request is submitted.
- It will only call
How to run the above /verify
calls in background based on the above flow is my question. Could anyone please help me here?
CodePudding user response:
There are multiple ways to may a non-blocking fire-and-forget call like this.
The simplest, IMO, is to use a separate thread to execute the call using a synchronous operation. Another is to use tooling that supports non-blocking calls.
In addition, there are frameworks that simplify this effort. Camel comes to mind. Of course, there is a fair amount of effort to use the framework itself.
CodePudding user response:
Instead of calling the other api endpoint you can simply use the service method which you have made for /veriy as then you do not have to call another end point. As you are using verify method in both cases. You can just simply call it everytime
And as you only want to call insertdb() when entity does not exist you can do that by checking it from database and using if condition
However if your requirement is to call another endpoint there is a spring RestTemplate class which you can use for api calls You can check about this from below link http://howtodoinjava.com/spring/spring-restful/spring-restful-client-resttemplate-example/
Also, below is a simple example of how this works
private static void getEmployees()
{
final String uri = "http://localhost:8080/springrestexample/employees.xml";
RestTemplate restTemplate = new RestTemplate();
String result = restTemplate.getForObject(uri, String.class);
System.out.println(result);
}