通过代码自定义
通过代码的方式自定义负责均衡策略时需要注意的是,注意避免SpringBoot的包扫描,因为自定义的规则必须在Eureka的规则实例化以后再实例化才会生效,那么这样就有两种方式,
了解springcloud架构可以加求求:三五三六二四七二五九
第一种
1.在CloudDemoConsumerApplication类上级新建包config,然后新建LoanBalanced类。使用此类注册一个IRule以达到替换Eureka的目的
package cn.org.config;
import com.netflix.loadbalancer.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class LoadBalanced {
@Bean
public IRule ribbonRule() {
return new RoundRobinRule(); //轮训
// return new WeightedResponseTimeRule(); //加权权重
//return new RetryRule(); //带有重试机制的轮训
//return new RandomRule(); //随机
//return new TestRule(); //自定义规则
}
}
2.注意包名,CloudDemoConsumerApplication的包名是cn.org.zhixiang。
3.想使用哪种负载均衡策略就new哪一种就ok
4.TestRule为自定义的规则:
package cn.org.config.domain;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.Server;
import java.util.List;
public class TestRule implements IRule {
private ILoadBalancer loadBalancer;
@Override
public Server choose(Object o) {
List<Server> servers= loadBalancer.getAllServers();
return servers.get(0);
}
@Override
public void setLoadBalancer(ILoadBalancer iLoadBalancer) {
this.loadBalancer=iLoadBalancer;
}
@Override
public ILoadBalancer getLoadBalancer() {
return this.loadBalancer;
}
}
如果有自定义的需求的话可以参照这个写法,我这只是测试使用,取的服务列表的第一个。
5.在CloudDemoConsumerApplication类上添加注解@RibbonClient(name = “provider-demo”, configuration = cn.org.config.LoadBalanced
.class),指定provider-demo服务使用的是LoadBalanced类提供的规则
第二种:
依旧把LoadBalanced放到cn.org.zhixiang包下,不过呢通过自定义注解来解决包扫描的问题
1.自定义一个注解
public @interface ExcludeFromComponentScan {
}
2.类使用刚才自定义的注解标示
@Configuration
@ExcludeFromComponentScan
public class AvoidLoanbalanced {
@Bean
public IRule ribbonRule() {
return new RoundRobinRule(); //轮训
// return new WeightedResponseTimeRule(); //加权权重
//return new RetryRule(); //带有重试机制的轮训
//return new RandomRule(); //随机
//return new TestRule(); //自定义规则
}
}
3.Application中指定包扫描忽略使用上方注解的类,然后注册规则
@RibbonClient(name = "provider-demo", configuration = AvoidLoanbalanced.class)
@ComponentScan(excludeFilters = { @ComponentScan.Filter(type = FilterType.ANNOTATION, value = ExcludeFromComponentScan.class) })
注意:上方两种方式使用一种就够了。