spring-bootrestspring-mvcasynchronousspring-async

Return an api response from rest controller and then do some processing async


I am new to spring boot and trying an interesting scenario. I want to return the result of an api and post that do some kafka and rabbitMQ publishing and I don't want my api response to halt till the time I am doing publishing. I am trying to use @EnableAsync to enable async processing in the application and @async to define my methods.

@Async
    fun publishOfferEventsAsync() {
        Thread.sleep(10000)
    // publish to rmq
        logger().debug { "xxxyyyzzz" }
    }

Can I directly call this async execution from other non-async methods of the bean? Is there a better way you can suggest. Thank you!


Solution

  • If both sync. and @Async are defined in different objects , it is okay.

    If they are defined in the same object , it is not okay simply because spring AOP which @Async is based on does not support self-invocation. (Refer this for details)

    If they really need to be defined in the same object , you can define another generic @Async executor bean and call the async. method via it. Something likes :

    @Service
    public class AsyncExecutor {
    
        @Async
        public <T> T execute(Supplier<T> action) {
            return action.get();
        }
    
        @Async
        public void execute(Runnable action) {
            action.run();
        }
    
    }
    
    

    And then inject it to use it :

    @Service
    public class FooService {
    
       @Autowired
       private AsyncExecutor asyncExecutor;
    
       public void someSyncMethod(){
         asyncExecutor.execute(()->publishOfferEventsAsync());
       }
    
       @Aysnc 
       public void publishOfferEventsAsync() {
          ...
       }
    
    }