java版spring cloud分布式微服务:自定义Eureka集群负载均衡策略

通过代码自定义
通过代码的方式自定义负责均衡策略时需要注意的是,注意避免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) })

注意:上方两种方式使用一种就够了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值