spring cloud中如何通过feign调整负载均衡规则

Posted

技术标签:

【中文标题】spring cloud中如何通过feign调整负载均衡规则【英文标题】:How can I adjust load balancing rule by feign in spring cloud 【发布时间】:2017-07-19 05:03:21 【问题描述】:

据我所知,feign 包含功能区的功能,我在代码中证明了这一点。

当我使用 feign 时,默认规则是 Round Robin Rule。 但是如何更改我的 feign 客户端代码中的规则,ribbon 是唯一的方法吗?

下面是我的代码,请帮忙。

ConsumerApplication.java

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
@EnableCircuitBreaker
public class ConsumerApplication 
    public static void main(String[] args) 
        SpringApplication.run(ConsumerApplication.class, args);
    

UserFeignClient .java

@FeignClient(name = "cloud-provider", fallback = UserFeignClient.HystrixClientFallback.class)
public interface UserFeignClient 
    @RequestMapping("/id")
    BaseResponse findByIdFeign(@RequestParam("id") Long id);

    @RequestMapping("/add")
    BaseResponse addUserFeign(UserVo userVo);

    @Component
    class HystrixClientFallback implements UserFeignClient 
        private static final Logger LOGGER = LoggerFactory.getLogger(HystrixClientFallback.class);

        @Override
        public BaseResponse findByIdFeign(@RequestParam("id") Long id) 
            BaseResponse response = new BaseResponse();
            response.setMessage("disable");
            return response;
        

        @Override
        public BaseResponse addUserFeign(UserVo userVo) 
            BaseResponse response = new BaseResponse();
            response.setMessage("disable");
            return response;
        
    

FeignController.java

@RestController
public class FeignController 

    @Autowired
    private UserFeignClient userFeignClient;

    @GetMapping("feign/id")
    public BaseResponse<Date> findByIdFeign(@PathVariable Long id) 
        BaseResponse response = this.userFeignClient.findByIdFeign(id);
        return response;
    

    @GetMapping("feign/user/add")
    public BaseResponse<Date> addUser() 
        UserVo userVo = new UserVo();
        userVo.setAge(19);
        userVo.setId(12345L);
        userVo.setUsername("nick name");
        BaseResponse response = this.userFeignClient.addUserFeign(userVo);
        return response;
    

【问题讨论】:

【参考方案1】:

来自documentation:

@RibbonClient(name = "cloud-provider", configuration = CloudProviderConfiguration.class)
public class ConsumerApplication  
    /* ... */


class CloudProviderConfiguration 
    @Bean
    public IRule ribbonRule(IClientConfig config) 
        return new RandomRule();
    

【讨论】:

但是如果我有多个provider,如何配置RibbonClient? 我明白了。只需使用@RibbonClients。 @Gabriel.ge,你介意在 github 上上传源代码吗?谢谢! @Prash,这里是gtihub地址。github.com/gabrielge/spring-cloud-consumer.git

以上是关于spring cloud中如何通过feign调整负载均衡规则的主要内容,如果未能解决你的问题,请参考以下文章

08 在Spring Cloud中使用Feign

Spring Cloud中Feign如何统一设置验证token

Spring Cloud中Feign如何统一设置验证token

Spring-Cloud之Feign

Spring Cloud Feign使用详解

如何将opentracing/jaeger与spring cloud、hystrix、feign集成?