Modify the Ribbon default load rule rule

Scenes

In spring cloud gateway, a load balancing strategy is added (the modification is the same). In most cases, it is configured with "service.ribbon.NFLoadBalancerRuleClassName=IRule.class". This method is only for a single service, because our services are relatively correct. The configuration of a single service is too cumbersome, so I want to achieve my goal by modifying the default configuration of Ribbon.

Program

Find the documentation: https://docs.spring.io/spring-cloud-netflix/docs/2.2.5.RELEASE/reference/html/#spring-cloud-ribbon

Found the @RibbonClients tag, which is a modification of the default configuration of Ribbon.

The implementation is as follows:

  • Create a new default configuration, set the ribbonRule method to set the default load rule, you can also use the ribbonPing, ribbonServerList, serverListFilter methods to configure other default parameters, not to mention here, please explore by yourself.
    
    import com.lizz.gateway.loadbalancer.VersionRoundRobinRule;
    import com.netflix.client.config.IClientConfig;
    import com.netflix.loadbalancer.IRule;
    import org.springframework.beans.factory.annotation.Configurable;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    /**
     * @description: 调整ribbon默认配置
     * 原始默认org.springframework.cloud.netflix.ribbon.RibbonClientConfiguration
     * @author: lizz
     */
    @Configuration(proxyBeanMethods = false)
    public class RibbonConfiguration {
        @Bean
        public IRule ribbonRule() {
            //自定义负载规则
            return new VersionRoundRobinRule();
        }
    }
    

     

  • Use @RibbonClients to enable the Ribbon default configuration
    import com.liubike.gateway.config.RibbonConfiguration;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cloud.netflix.ribbon.RibbonClients;
    
    
    /**
     * 程序启动类
     *
     * @author: lizz
     */
    @SpringBootApplication
    @RibbonClients(defaultConfiguration = RibbonConfiguration.class)
    public class GatewayApplication {
        public static void main(String[] args) {
            SpringApplication.run(GatewayApplication.class, args);
        }
    }
     

Guess you like

Origin blog.csdn.net/lizz861109/article/details/110199142