我正在尝试使用spring-hateoas
将HATEOAS应用于我的spring boot应用程序。直到我将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的
ResourceAssembler<T, D>
接口并覆盖toResource
方法。有什么办法可以解决这个问题?
最佳答案
我不确定是否可以将其视为答案,这更像是一种变通方法:
@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
中)放入了另一个方法中。它是这样工作的,但绝对不是一种干净的方法。因此,如果有人知道如何更好地解决此问题。