这个Async HystrixCommand有什么问题吗?

时间:2017-06-14 08:31:02

标签: asynchronous spring-cloud spring-cloud-netflix hystrix spring-cloud-sleuth

我需要不时发送通知,我异步执行此任务。我正在使用如下的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命令可以解决这个问题

2 个答案:

答案 0 :(得分:3)

是否从同一类中的方法调用方法notify?如果是这种情况,请尝试直接从另一个类调用方法notify,其中notify方法的封闭类被作为依赖项注入。

基本上,请尝试这样做:

enter image description here

而不是:

enter image description here

答案 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 .