2
我在這裏借用以下代碼Spring blog。RestTemplate或discoveryClient - 在Spring Cloud應用程序中使用哪一個?
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class Application {
public static void main(String[] args) {
new SpringApplicationBuilder(Application.class)
.web(false)
.run(args);
}
}
@Component
class DiscoveryClientExample implements CommandLineRunner {
@Autowired
private DiscoveryClient discoveryClient;
@Override
public void run(String... strings) throws Exception {
discoveryClient.getInstances("photo-service").forEach((ServiceInstance s) -> {
System.out.println(ToStringBuilder.reflectionToString(s));
});
discoveryClient.getInstances("bookmark-service").forEach((ServiceInstance s) -> {
System.out.println(ToStringBuilder.reflectionToString(s));
});
}
}
@Component
class RestTemplateExample implements CommandLineRunner {
@Autowired
private RestTemplate restTemplate;
@Override
public void run(String... strings) throws Exception {
// use the "smart" Eureka-aware RestTemplate
ResponseEntity<List<Bookmark>> exchange =
this.restTemplate.exchange(
"http://bookmark-service/{userId}/bookmarks",
HttpMethod.GET,
null,
new ParameterizedTypeReference<List<Bookmark>>() {
},
(Object) "mstine");
exchange.getBody().forEach(System.out::println);
}
}
有兩種從其他微服務中消費微服務端點的選項。
RestTemplate
- 提供負載平衡功能,負載均衡請求。但是如果我的服務在3個節點上運行,RestTemplate是否知道一個節點是關閉還是響應,並且「智能」地在兩個節點之間進行負載平衡。- 使用
DiscoveryClient
獲取服務實例併發出請求(如上所示)。在這種情況下,雖然沒有負載均衡,但我認爲返回的服務實例是響應式的。
後者失去負載平衡的功能,但提供一種主動服務實例
前者進行負載平衡,但所得到的實例可以是無活性的。
我想知道哪個是首選使用?
如果我上面的理解不正確,請糾正我。