Reputation: 1446
I have a very simple controller like this :
@RequestMapping(value = "food", method = RequestMethod.POST)
public ResponseEntity<?> getAll(@RequestParam("term") String term) {
List<Food> foods = foodService.findByNameMatching(term);
return new ResponseEntity<>(foods, HttpStatus.OK);
}
And the service :
@Service
@Transactional
public class FoodService {
@Autowired
private FoodRepository foodRepository;
public List<Food> findByNameMatching(String name) {
return foodRepository.findMatchName(name);
}
}
The FoodRepository is nothing but just a JpaRepository .
So far the flow will be : Controller --> Service --> Repository
For now , I want all of my Rest API will support asynchonous.In this case, the service call the repository to query data. Should I put the @Async annotation to the FoodService's method to make the query task to be asynchronous?.
@Async
public List<Food> findByNameMatching(String name) {
return foodRepository.findMatchName(name);
}
In extension, should I put the @Async annotation all of my service's methods to make my application fully support asynchronous?.
So far as I know, the @Async annotation in Spring support asynchronous while the Callable and the DeferredResult do the same thing , so which case should I choose which one?.
Upvotes: 0
Views: 983
Reputation: 1937
@Async works in combination with Future int he service and DefferedResult in the controller. See http://spring.io/guides/gs/async-method/
Your FoodService.findByNameMatching has to return java8 CompetableFuture or Spring ListenableFuture or just Future. And your controller would return DefferedResult.
@Async
public CompletableFuture<List<Food>> findByNameMatching(String name) {
return CompletableFuture.completedFuture(foodRepository.findMatchName(name));
}
Don't forget to make your pplication AsyncEnabled. With spring boot you can use @EnableAsync.
Those APIs that you want to work asynchronously should be changed according to above comments.
Upvotes: 1