Ribbon的幾種配置方式詳解
阿新 • • 發佈:2018-11-09
文章目錄
Ribbon的自定義配置(java程式碼方式)生效條件
- 第一種方式:將TestConfiguration類放在application啟動類上層
- 第二種方式:將TestConfiguration類放在application啟動類同層及以下,
- 需在application啟動類上添加註解
@ComponentScan(excludeFilters = { @ComponentScan.Filter(type = FilterType.ANNOTATION, value = ExcludeFromComponentScan.class) })
- 需在application啟動類同層新增介面類ExcludeFromComponentScan.java:
package com.mmzs.cloud; public @interface ExcludeFromComponentScan { }
- 並在ExcludeFromComponentScan.class介面添加註解@ExcludeFromComponentScan;並且註釋如下內容:
@Autowired IClientConfig config;
Ribbon的注意事項
0、Ribbon的自定義配置優先順序:
配置檔案>java程式碼>預設配置
1、自定義配置時,@Configuration和@ComponentScan包不應重疊
- 示例:
@RibbonClient(name = "microservice-provider-user", configuration = TestConfiguration.class) @ComponentScan(excludeFilters = { @ComponentScan.Filter(type = FilterType.ANNOTATION, value = ExcludeFromComponentScan.class) })
2、使用RestTemplate時,想要獲得一個List時,應該用陣列,而不應該直接用List
- 錯誤用法
List<User> users = this.restTemplate.getForObject("http://microservice-provider-user/list-all/", List.class);
for (User user : users) {
System.out.println("輸出:" + user.getId() + "+" + user.getUsername());
}
- 正確用法
User[] users = this.restTemplate.getForObject("http://microservice-provider-user/list-all", User[].class);
List<User> lists = Arrays.asList(users);
for (User user : lists) {
System.out.println("輸出:" + user.getId() + "+" + user.getUsername());
}