Spring @Async with CompletableFuture

前端 未结 1 596
别跟我提以往
别跟我提以往 2020-12-13 07:24

I have a doubt about this code:

@Async
public CompletableFuture doFoo() {
    CompletableFuture fooFuture = new CompletableFuture         


        
相关标签:
1条回答
  • 2020-12-13 07:47

    Spring actually does all of the work behind the covers so you don't have to create the CompletableFuture yourself. Basically, adding the @Async annotation is as if you called your original method (without the annotation) like:

    CompletableFuture<User> future = CompletableFuture.runAsync(() -> doFoo());
    

    As for your second question, in order to feed it to an executor, you can specify the exectutor bean name in the value of the @Async annotation, like so:

        @Async("myExecutor")
        public CompletableFuture<User> findUser(String usernameString) throws InterruptedException {
            User fooResult = longOp(usernameString);
            return CompletableFuture.completedFuture(fooResult);
        }
    

    The above would basically be the following as if you called your original method, like:

    CompletableFuture<User> future = CompletableFuture.runAsync(() -> doFoo(), myExecutor);
    

    And all of your exceptionally logic you would do with the returned CompletableFuture from that method.

    0 讨论(0)
提交回复
热议问题