What's wrong with this Async HystrixCommand?
I need to send notifications from time to time, I do this task asynchronously. I am using HystrixCommand as shown below to make an asynchronous RestTemplate call that doesn't work:
@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 tried to do before (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();
}
PS: The reason for adding the sleuth to the tags is because doing this on a new thread does not apply to headers (baggage- *), so try to get the Hystrix team to do the trick
source to share
When using, Runnable
you need to wrap them in a trace. those. TraceRunnable
... It's there in the docs - http://cloud.spring.io/spring-cloud-sleuth/spring-cloud-sleuth.html#_runnable_and_callable .
As for why the Hystrix stuff isn't working - most likely it's linked from https://github.com/spring-cloud/spring-cloud-sleuth/issues/612 .
source to share