3

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

}

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

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

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

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

我想知道哪个是首选使用?

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

4

1 回答 1

1

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

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

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

于 2017-04-25T06:44:24.953 回答