【问题标题】:RestTemplate or discoveryClient - which one to use in Spring Cloud application?RestTemplate 或 discoveryClient - 在 Spring Cloud 应用程序中使用哪一个?
【发布时间】:2015-11-01 05:30:41
【问题描述】:

我从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);
    }

}

从其他微服务使用微服务端点有两种选择。

  1. RestTemplate - 提供负载均衡功能,对请求进行负载均衡。但是,如果我有一个在 3 个节点中运行的服务,RestTemplate 是否知道一个节点是否已关闭或响应,并且仅在其中两个节点之间进行“智能”负载平衡。
  2. 使用DiscoveryClient 获取服务实例并发出请求(如上所示)。在这种情况下,虽然不是负载均衡,但我认为返回的服务实例是响应式的。

后者失去了负载均衡功能,但提供了一个活跃的服务实例

以前的负载平衡,但生成的实例可能处于非活动状态。

我想知道哪个是首选?

如果我上面的理解不正确,请纠正我。

【问题讨论】:

    标签: spring-boot spring-cloud netflix-eureka


    【解决方案1】:

    使用resttemplate的第一个选项是更好的选择

    我们只需要在 resttemplate 上注解 @LoadBalanced 并有一个 zuul 代理服务器作为边缘服务器。如果我们这样做,那么对边缘服务器的任何请求都将默认使用功能区进行负载平衡,而 resttemplate 将以循环方式路由请求。

    如果我们使用 Discoverclient,那么我们就无法跨各种实例路由请求。

    【讨论】:

      猜你喜欢
      • 2016-07-27
      • 2021-02-02
      • 1970-01-01
      • 2019-08-03
      • 2019-01-28
      • 2018-05-08
      • 2018-10-16
      • 1970-01-01
      • 2017-02-10
      相关资源
      最近更新 更多