SpringCloud(一):Ribbon-几种配置方式

  |   0 评论   |   117 浏览

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());
    }    

标题:SpringCloud(一):Ribbon-几种配置方式
作者:mmzsblog
地址:https://www.mmzsblog.cn/articles/2019/08/06/1565077811130.html

个人微信公众号 ↓↓↓                 


评论

发表评论