我使用Spring-Cloud-Netflix在微服务之间进行通信。假设我有两个服务,Foo和Bar,而Foo使用Bar的REST端点之一。我使用带有以下注释的接口@FeignClient
:
@FeignClient
public interface BarClient {
@RequestMapping(value = "/some/url", method = "POST")
void bazzle(@RequestBody BazzleRequest);
}
然后,我SomeService
在Foo中有一个服务类,称为BarClient
。
@Component
public class SomeService {
@Autowired
BarClient barClient;
public String doSomething() {
try {
barClient.bazzle(new BazzleRequest(...));
return "so bazzle my eyes dazzle";
} catch(FeignException e) {
return "Not bazzle today!";
}
}
}
现在,为了确保服务之间的通信正常,我想构建一个测试,使用WireMock之类的东西向伪造的Bar服务器触发真实的HTTP请求。测试应确保伪装正确解码服务响应并将其报告给SomeService
。
public class SomeServiceIntegrationTest {
@Autowired SomeService someService;
@Test
public void shouldSucceed() {
stubFor(get(urlEqualTo("/some/url"))
.willReturn(aResponse()
.withStatus(204);
String result = someService.doSomething();
assertThat(result, is("so bazzle my eyes dazzle"));
}
@Test
public void shouldFail() {
stubFor(get(urlEqualTo("/some/url"))
.willReturn(aResponse()
.withStatus(404);
String result = someService.doSomething();
assertThat(result, is("Not bazzle today!"));
}
}
我如何将这样的WireMock服务器注入eureka,以便让feign能够找到它并与之通信?我需要哪种注释魔术?
使用Spring的RestTemplate代替伪装。RestTemplate还能够通过eureka解析服务名称,因此您可以执行以下操作:
@Component
public class SomeService {
@Autowired
RestTemplate restTemplate;
public String doSomething() {
try {
restTemplate.postForEntity("http://my-service/some/url",
new BazzleRequest(...),
Void.class);
return "so bazzle my eyes dazzle";
} catch(HttpStatusCodeException e) {
return "Not bazzle today!";
}
}
}
使用Wiremock比伪装更容易测试。
但这肯定不会使用Feign,如果您使用RestTemplate,那是有效的,但是问题是关于SpringBoot的Feign。人们使用Feign是因为它比RestTemplate更好...
这不能回答原始问题。您已经完全改变了策略,这意味着原始问题并不适用于您,但它仍然是一个有效的问题(而这正是我正在尝试做的事情),但这并不是答案。
@haggisandchips随便。对我来说,它可以解决问题:)
真的不明白为什么每个人都讨厌我的回答。毕竟这是我的问题。这是我当时非常适合的解决方案。无论如何,我不再使用spring-cloud,因为整个过程有点胡扯和不稳定
也许,如果您回答了这个问题,那么人们会投票赞成。顺便说一句,如果您使用发现服务,那么RestTemplate是一个非常糟糕的解决方案,因为它们不是开箱即用的发现意识。