Reputation: 197
I have this code
private Boolean doSomething() {
// SOME CODE
this.sync();
return true;
}
public void sync() {
RestTemplate restTemplate = restTemplate();
restTemplate.exchange(batchHost, HttpMethod.GET, header(), String.class);
}
I don't need data from the rest call. it's batch execution service he take times. but for my doSomething
function i don't need a response from sync
to continue.
Today, when the rest call not working, not available... my function doSomething .... do nothing...
How to call rest service but continue without error doSomething()
without errors ??
Thanks
I use java 11
Upvotes: 1
Views: 12839
Reputation: 1
If you dont want a response from the methods you run async, then You can simply do the async portion inside completableFuture
lambda method as follows, directly in your triggering endpoint and return 200 ok immediately. Note, if internal method may throw exceptions, you need to swallow that too in a try/catch to ensure it happens asynch. as well.
@GetMapping(value = "/trigger")
public ResponseEntity<String> triggerMethod() throws Exception {
CompletableFuture.runAsync(() -> {
try {
this.dosomething();
} catch(Exception e) {e.printStackTrace();}
});
return new ResponseEntity<String>(HttpStatus.OK);
}
However, if you require a response through other methods run asynchronously, then you will need to implement something like this example
Upvotes: 0
Reputation: 1058
You can use Spring WebFlux to build or consume API's in reactive and non-blocking manners. Here is the official documentation which explains this in detail: https://docs.spring.io/spring-framework/docs/current/reference/html/web-reactive.html
Upvotes: 0
Reputation: 2754
You can make the sync
method call asynchronous. Spring provides easy way to do that. Add @EnableAsync
in any of you Configuration class (i.e. Classes annotated with @Configuration
). If you don't find any configuration class then add @EnableAsync
in the class with @SpringBootApplication
.
@SpringBootApplication
@EnableAsync
public class SpringbootApplication{
public static void main(String[] args) {
SpringApplication.run(SpringbootApplication.class, args);
}
}
Then add @Async
to your sync
method. Your code will look like this.
@Async
public void sync() {
RestTemplate restTemplate = restTemplate();
restTemplate.exchange(batchHost, HttpMethod.GET, header(), String.class);
}
To make @Async
work, this sync
method need to be called from another class file. If you call sync
from same class then sync method will not be asynchronous.
Upvotes: 6
Reputation: 580
You should not use RestTemplate to call REST API.
"Please, consider using the org.springframework.web.reactive.client.WebClient which has a more modern API and supports sync, async, and streaming scenarios."
Upvotes: 0