ribbon中自定义负载均衡算法

「这是我参与11月更文挑战的第18天,活动详情查看:2021最后一次更文挑战

ribbon是Netflix开源的一款用于客户端负载均衡的软件工具,它在集群中为各个客户端的通信提供了支持,有助于控制HTTP和TCP客户端的行为,提供了很多负载均衡的算法,例如轮询,随机等,同时也可以实现自定义的算法。

在Spring Cloud 构建的微服务中,Ribbon作为服务消费者的负载均衡器,有两种使用方式,一种是与RestTemplate相结合,另一种是与Feign相结合。Feign已经默认集成了Ribbon,并且关于Feign的相关知识我们将在第4章进行详细讲解。

Ribbon包含很多子模块,但很多子模块没有用于生产环境,目前用于生产的Ribbon的子模块具体如下:

● ribbon-core:包括定义负载均衡接口、客户端接口、内置的负载均衡实现等API。

● ribbon-eureka:提供eureka客户端实现负载均衡的API。

● ribbon-httpclient:对Apache的HttpClient进行封装,该模块提供了含有负载均衡功能的REST客户端。

Spring Cloud也允许开发人员声明额外的配置(在RibbonClientConfiguration之上)-@RibbonClient来取得客户端的全部控制权。例如:

@Configuration
@RibbonClient(name = "foo", configuration = FooConfiguration.class)
public class TestConfiguration {
}
复制代码

本例中,客户端由已在RibbonClientConfiguration中的组件以及FooConfiguration中的任意组件组成(后者通常覆盖前者)。

警告 FooConfiguration必须有@Configuration,但注意它并不在主应用上下文的@ComponentScan中,否则它会被所有的@RibbonClients分享(意思就是覆盖所有客户端的默认值)。如果开发人员使用@ComponentScan(或@SpringBootApplication),那就必须采取措施避免被覆盖到(==例如将其放入一个独立的,不重叠的包中==,或以@ComponentScan指明要扫描的包。

引入pom依赖

 <!--引入ribbon-->
 <dependency>
       <groupId>org.springframework.cloud</groupId>
       <artifactId>spring-cloud-starter-ribbon</artifactId>
       <version>1.4.6.RELEASE</version>
 </dependency>
 <!--引入erueka-->
 <dependency>
     <groupId>org.springframework.cloud</groupId>
     <artifactId>spring-cloud-starter-eureka</artifactId>
     <version>1.4.6.RELEASE</version>
</dependency>
复制代码

配置erueka

# 配置eureka
eureka:
  client:
    register-with-eureka: false # 不向eureka注册自己
    service-url:    # 获取服务的地址
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/

复制代码

在主启动类上开启服务

@SpringBootApplication
@EnableEurekaClient // eureka客户端
@RibbonClient(name = "SPRINGCLOUD-PROVIDER-DEPT",configuration = MyRule.class )
public class DeptConsumer {
    public static void main(String[] args) {
        SpringApplication.run(DeptConsumer.class,args);
    }
}

复制代码

创建配置类

注意配置类存放的包,不能跟启动类平级 在这里插入图片描述MyRule类中进行springboot配置类的声明

@Configuration // 表明其为基本的配置类
public class MyRule {
     @Bean // 把组件放入ioc容器中
     public IRule myrule(){
         return  new  MyRandomRule();
     }
}
复制代码

定义自己的类MyRule实现负载均衡算法,自定类应该继承父类AbstractLoadBalancerRule(接口IRule的实现类都继承了该类)

最后启动,检验自己的负载均衡算法

猜你喜欢

转载自juejin.im/post/7031900273912053797
今日推荐