【问题标题】:How can I adjust load balancing rule by feign in spring cloudspring cloud中如何通过feign调整负载均衡规则
【发布时间】: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;
    }
}

【问题讨论】:

    标签: spring spring-cloud netflix-feign netflix-ribbon


    【解决方案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
    猜你喜欢
    • 2021-10-22
    • 2019-08-22
    • 1970-01-01
    • 1970-01-01
    • 2016-10-07
    • 2019-08-22
    • 2016-07-20
    • 2020-10-06
    • 2022-01-18
    相关资源
    最近更新 更多