Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we use @Async on a @HystrixCommand

I don't know how to test this and need a quick answer whether it is possible, and how could I possibly test this.

So i have an api-gateway call from a service, and what i want to know is that if following is possible with spring boot

@Component
class GatewayService {

      @Autowired
      private MicroserviceGateway microServiceGateway;

      @Async
      @HystrixCommand(threadPool = "microservice", groupKey = "microService", fallback = "getResponse2")
      private Future<ResponseDTO> getResponse(RequestDTO request) {
         try {
               ResponseDTO response = new APIRequest(endpoint, api).body(request).post();
               return new AsyncResult(response);
         } catch (Exception e) {
             throw new GatewayServiceException(e);
         }
      } 

      public Future<ResponseDTO> getResponse2(RequestDTO request) {
           return Futures.immediateFuture(RequestDTO.empty());
      }

}

Will the fallback work? will it all be async?

EDIT : Tried this, and hystrix is being ignored, since the future is returned immediately. Any work arounds? solutions?

like image 526
Mudasir Ali Avatar asked Feb 04 '23 10:02

Mudasir Ali


1 Answers

I believe the approach to use Hystrix commands asynchronously using a thread pool would be:

If using @HystrixCommand annotation:

...
    @HystrixCommand
    public Future<Product> findProduct(String id) {
        return new AsyncResult<Product>() {

            @Override
            public Product invoke() {
                ...
                return productService.find ...
            }
        };
    }
...

If using a Hystrix command class, for instance ProductCommandFind.java

...
        ProductCommandFind command = new ProductCommandFind(...);
        Future<Product> result = command.queue();
...

Hystrix command uses its own and configurable threadpool, maybe configuring a thread pool per command group, lets say a thread pool for command group named PRODUCT_GROUP used by commands: productCommandFind, productCommandCreate, ....

Basically I don't think there is a need to annotate a method with @Async and @HystrixCommand at the same time.

like image 79
ootero Avatar answered Feb 07 '23 00:02

ootero