HystrixCommand注释导致ControllerLinkBuilder中断

时间:2015-10-06 12:20:29

标签: java spring spring-mvc spring-boot spring-hateoas

我尝试使用spring-hateoas HATEOAS 应用于我的春季启动应用程序。这很好用,直到我将REST调用包裹在HystrixCommand

@HystrixCommand(fallbackMethod = "myFallbackMethod")
@RequestMapping(method = RequestMethod.GET, value = "/path")
public ResponseEntity<Resources<Resource<Data>>> getAllData() {
    String url = "http://localhost:8080/someotherpath"

    ParameterizedTypeReference<Iterable<Data>> responseType = new ParameterizedTypeReference<Iterable<Data>>() {};
    ResponseEntity<Iterable<Data>> response = restTemplate.exchange(url, HttpMethod.GET, null, responseType);

    if (response.getStatusCode().is2xxSuccessful()) {
        Iterable<Data> data = response.getBody();
        Resources<Resource<Data>> resources = assembler.toResource(data);
        return new ResponseEntity<>(resources, response.getHeaders(), response.getStatusCode());
    }
    return new ResponseEntity<>(response.getHeaders(), response.getStatusCode());
}

我的汇编程序类将Data对象包装到Resource对象中现在会抛出此错误:Could not find current request via RequestContextHolder

如果我评论HystrixCommand注释,则错误消失,一切正常。

我的汇编程序类只是实现了Springs&#39; ResourceAssembler<T, D>接口并覆盖toResource方法。

有什么方法可以解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

我不确定我是否可以将此视为答案,更像是一种解决方法:

@RequestMapping(method = RequestMethod.GET, value = "/path")
public ResponseEntity<Resources<Resource<Data>>> getAllData() {
    return getAllDataImpl()
}

@HystrixCommand(fallbackMethod = "myFallbackMethod")
public ResponseEntity<Resources<Resource<Data>>> getAllDataImpl() {
    String url = "http://localhost:8080/someotherpath"

    ParameterizedTypeReference<Iterable<Data>> responseType = new ParameterizedTypeReference<Iterable<Data>>() {};
    ResponseEntity<Iterable<Data>> response = restTemplate.exchange(url, HttpMethod.GET, null, responseType);

    if (response.getStatusCode().is2xxSuccessful()) {
        Iterable<Data> data = response.getBody();
        Resources<Resource<Data>> resources = assembler.toResource(data);
        return new ResponseEntity<>(resources, response.getHeaders(), response.getStatusCode());
    }
    return new ResponseEntity<>(response.getHeaders(), response.getStatusCode());
}

我已经将实际执行http请求的方法的内容(并且需要包装到HystrixCommand中)放在另一个方法中。 它以这种方式工作,但它绝对不是一个干净的方式。所以,如果有人知道如何以更好的方式解决这个问题。