• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
Y-wee
博客园    首页    新随笔    联系   管理     

配置Ribbon负载均衡策略

配置Ribbon负载均衡策略

导入依赖,如果已经导入了spring-cloud-starter-netflix-eureka-client依赖则不用再导入下面的依赖,因为spring-cloud-starter-netflix-eureka-client依赖中包含了ribbon的依赖

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
    <version>2.2.1.RELEASE</version>
    <scope>compile</scope>
</dependency>

创建配置类,官方文档明确给出了警告:

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

所以需要在@ComponentScan所扫描的当前包及子包之外创建配置类

package com.yl.myrule;


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

/**
 * Ribbon负载均衡策略配置
 *
 * @Y-wee
 */
@Configuration
public class MyRule {

    /**
     * RoundRobinRuLe:轮询
     * RandomRule:随机
     * AvailabilityFilteringRule:会先过滤掉故障的服务,然后选择并发较小的实例
     * RetryRule:会先按照轮询获取服务,如果服务获取失败,则会在指定的时间内进行重试,获取可用服务
     * WeightedResponseTimeRule:RoundRobinRuLe的扩展,响应速度越快的实例选择权重越大,越容易被选择
     * BestAvailableRule:会先过滤掉由于多次访问故障而处于断路器跳闸状态的服务,然后选择一个并发量最小的服务
     * ZoneAvoidanceRule:默认规则,复合判断server所在区域的性能和server的可用性选择服务器
     * @return
     */
    @Bean
    public IRule rule(){
        return new RandomRule();
    }

}

主启动类添加@RibbonClient注解

package com.yl.order;

import com.yl.myrule.MyRule;
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
// 在启动该服务的时候就能去加载自定义Ribbon配置类,从而使配置生效(name:要调用的服务名)
@RibbonClient(name = "PAYMENT",configuration = MyRule.class)
public class Order80Application {

    public static void main(String[] args) {
        SpringApplication.run(Order80Application.class,args);
    }

}
记得快乐
posted @ 2021-03-06 16:05  Y-wee  阅读(177)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3