我需要不时发送通知,我异步执行此任务。我正在使用如下的HystrixCommand来执行不起作用的异步RestTemplate调用:
@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;
}
};
}
这是我之前尝试做的事情(也没有用):
@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:将标签添加到标签的原因是,在新线程中执行此操作不会传播标头(行李 - *),因此尝试这样希望Hystrix命令可以解决这个问题
答案 0 :(得分:3)
答案 1 :(得分:2)
When using Runnable
you have to wrap them in a trace representation. i.e. 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 doesn't work - most likely it's related to https://github.com/spring-cloud/spring-cloud-sleuth/issues/612 .