我开始在我的应用程序上使用Hystrix来处理来自外部服务的数据。我的代码中的一些要点:
const fs = require('fs')
const http = require('http')
const os = require('os')
const path = require('path')
startServer() {
// GETTING NETWORK IP OF THE SERVER (ipv4, e.g. 192.168.0.x)
var interfaces = os.networkInterfaces()
var addresses = []
for (var k in interfaces) {
for (var k2 in interfaces[k]) {
var address = interfaces[k][k2];
if (address.family === 'IPv4' && !address.internal) {
addresses.push(address.address)
}
}
}
var filtered = addresses.filter(x => x.includes("192.168.0"))
// SERVING FILE FOR OTHER LOCAL DEVICES
const hostname = filtered
const port = 8080
var fileName = "1.png"
var filePath = path.join("C:/Users/u/Desktop", fileName)
const server = http.createServer((req, res) => {
var stat = fs.statSync(filePath);
res.writeHead(200, {
'Content-Type': 'application/octet-stream',
"Content-Disposition": "attachment; filename=" + fileName
});
var readStream = fs.createReadStream(filePath);
// replacing all the event handlers with a simple call to readStream.pipe()
readStream.pipe(res);
})
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`)
})
}
在我的单元测试中,我想测试后备情况,例如当外部服务返回404 Not Found响应时,所以我模拟我的测试如下:
@HystrixCommand(fallbackMethod = "getImagesFallback")
public ImageResultResource getImages(String url)
{
ResponseEntity<ResultResource> result = restTemplate.exchange(url, HttpMethod.GET, new HttpEntity<>(getRequestHeaders()), ResultResource.class);
return result.getBody().getImageResultResource();
}
public ImageResultResource getImagesFallback(String url, Throwable e)
{
return new ImageResultResource();
}
但是当我运行测试时,似乎我没有调用上面定义的fallbackMethod。它直接返回我找不到的404 Not Found,我预计应该在这里捕获fallbackMethod,并且不会抛出404 Not Found。
任何人都可以给我提示如何在这种情况下测试我的fallbackMethod,还是我在这里配置有问题?非常感谢你!
答案 0 :(得分:0)
您的回退方法需要与具有HystrixCommand注释的方法具有相同的签名,或者具有添加Throwable的相同签名。 Here是相关的Javanica文档
public ImageResultResource getImagesFallback(String url, Throwable e) {
return new ImageResultResource();
}
答案 1 :(得分:0)
Hystrix自定义回退方法抛出具有HystrixRuntimeException实例的异常。 因此,您需要捕获此异常并使用它的getMessage方法进行打印。