我从Spring blog借用了下面的代码在这里。
@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
获取服务实例并发出请求(如上所示)。在这种情况下,虽然没有负载平衡,但我认为返回的服务实例是响应式的。
后者失去了负载均衡功能但提供了一个活跃的服务实例
前一个负载平衡但结果实例可能不活动。
我想知道哪个是首选?
以上理解有误请指正。
最佳答案
第一个选择使用resttemplate是一个更好的选择
我们只需要用 @LoadBalanced 并有一个 zuul 代理服务器作为边缘服务器。如果我们这样做,那么对边缘服务器的任何请求都将默认使用功能区进行负载平衡,并且 resttemplate 将以循环方式路由请求。
如果我们使用 Discoverclient,则我们无法跨多个实例路由请求。
关于spring-boot - RestTemplate 或 discoveryClient - 在 Spring Cloud 应用程序中使用哪一个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31900281/