简体   繁体   中英

Should i put @Async on every service method to make my application fully support asynchronous in Spring?

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?.

@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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM