Search code examples
asynchronousspring-cloudspring-cloud-netflixhystrixspring-cloud-sleuth

Whats wrong with this Async HystrixCommand?


I need to send notifications from time to time, I perform this task asynchronously. I'm using HystrixCommand as below to perform an asynchronous RestTemplate call which is not working:

@HystrixCommand
    public Future<String> notify(final Query query) {
        return new AsyncResult<String>() {
            @Override
            public String invoke() {
                String result = null;
                try {
                    ResponseEntity<HashMap> restExchange = restTemplate.exchange(url,
                            HttpMethod.POST,
                            new HttpEntity<String>(mapper.writeValueAsString(queryMap), httpHeaders),
                            HashMap.class);
                    LOGGER.info("Response code from " + url + " = " + restExchange.getStatusCodeValue());
                    result = ""+ restExchange.getStatusCodeValue();
                } catch(Exception e) {
                    LOGGER.error("Exception while sending notification! Message = " + e.getMessage(), e);
                }
                return result;
            }
        };
    }

This is what I was trying to do earlier(which didn't work either):

@HystrixCommand
    public String notify(final Query query) {
        new Thread(new Runnable() {
            @Override
            public void run() {

                try {
                    ResponseEntity<HashMap> restExchange = restTemplate.exchange(url, HttpMethod.POST,
                            new HttpEntity<String>(mapper.writeValueAsString(queryMap), httpHeaders), HashMap.class);
                    LOGGER.info("Response code from " + url + " = " + restExchange.getStatusCodeValue());

                } catch (Exception e) {
                    LOGGER.error("Exception while sending notification! Message = " + e.getMessage(), e);
                }

            }
        }).start();
    }  

P.S: Reason for adding sleuth to the tags is, performing this in a new Thread does not propagate the headers(baggage-*) so trying this hoping the Hystrix command will do the trick


Solution

  • Is the method notify being called from a method in the same class? If that is the case, try calling the method notify directly from a different class where the notify method's enclosing class is injected as a dependency.

    Basically, try doing this:

    enter image description here

    Instead of this:

    enter image description here