2015-08-09 25 views
2

我在這裏借用以下代碼Spring blogRestTemplate或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); 
    } 

} 

有兩種從其他微服務中消費微服務端點的選項。

  1. RestTemplate - 提供負載平衡功能,負載均衡請求。但是如果我的服務在3個節點上運行,RestTemplate是否知道一個節點是關閉還是響應,並且「智能」地在兩個節點之間進行負載平衡。
  2. 使用DiscoveryClient獲取服務實例併發出請求(如上所示)。在這種情況下,雖然沒有負載均衡,但我認爲返回的服務實例是響應式的。

後者失去負載平衡的功能,但提供一種主動服務實例

前者進行負載平衡,但所得到的實例可以是無活性的。

我想知道哪個是首選使用?

如果我上面的理解不正確,請糾正我。

回答

0

使用resttemplate的第一個選項是一個更好的選擇

我們只需要批註與 @LoadBalanced的resttemplate並有zuul代理服務器作爲邊緣服務器。如果我們這樣做了,那麼對邊緣服務器的任何請求將默認使用功能區進行負載平衡,而resttemplate將以循環方式路由請求。

如果我們使用Discoverclient,那麼我們不能通過各種實例路由請求。

相關問題