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
- ==错误用法==
Listusers = 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); Listlists = Arrays.asList(users); for (User user : lists) { System.out.println("輸出:" + user.getId() + "+" + user.getUsername()); } 复制代码