Ribbon 负载规则替换

1 添加规则类:

注意: 官方文档明确给出了警告:

Ribbon 负载规则替换_第1张图片

 

 

 这个自定义配置类不能放在 @ComponentScan 所扫描的当前包下以及子包下,否则自定义的配置类就会被所有的 Ribbon 客户端所共享,达不到特殊化定制的目的了。

Ribbon 负载规则替换_第2张图片

 

 

 

package com.atguigu.myrule;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RandomRule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 自定义负载均衡规则类
 */
@Configuration
public class MySelfRule {
    @Bean
    public IRule myRule(){
        return new RandomRule();
    }
}
 

2 主启动类添加 @RibbonClient

在启动该微服务的时候就能去加载我们的自定义 Ribbon 配置类,从而使配置生效

package com.atguigu.springcloud;
import com.atguigu.myrule.MySelfRule;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.ribbon.RibbonClient;

@SpringBootApplication
@EnableEurekaClient
@RibbonClient(name = "CLOUD-PROVIDER-SERVICE",configuration = MySelfRule.class)
public class OrderMain80 {
    public static void main(String[] args) {
        SpringApplication.run(OrderMain80.class,args);
    }
}
 

3 测试

Ribbon 负载规则替换_第3张图片

 

 多次刷新,是随机出现 serverPort ,负载规则就更改为随机了。

你可能感兴趣的:(Ribbon 负载规则替换)