我从这里的Spring 博客借用了下面的代码。
@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
获取服务实例并发出请求(如上所示)。在这种情况下,虽然没有负载平衡,但我认为返回的服务实例是响应式的。
后者失去了负载均衡功能,但提供了一个活跃的服务实例
前者负载平衡,但生成的实例可能处于非活动状态。
我想知道哪个是首选使用?
如果我上面的理解不正确,请纠正我。