spring cloud之ribbon负载均衡-自定义负载均衡配

2020-10-23  本文已影响0人  dancer4code

1.依赖导入

<!--version没有添加,我在父工程中添加了-->
<!--web应用导入-->
     <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
<!--eureka中包含了ribbon,不需要单独引入依赖-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
<!--添加ribbon失败重试机制-->
        <dependency>
            <groupId>org.springframework.retry</groupId>
            <artifactId>spring-retry</artifactId>
        </dependency>

2.配置

server:
  port: 6064

logging:
  level:
    com.d4c: debug

eureka:
  instance:
    prefer-ip-address: false
  client:
    register-with-eureka: true
    fetch-registry: true
    service-url:
      zone-1: http://peer1:6001/eureka/
      zone-2: http://peer2:6002/eureka/
spring:
  cloud:
    loadbalancer:
      retry:
        enabled: true # 开启Spring Cloud的重试功能
  application:
    name: consumer-ribbon

ribbon:
  restclient:
    enabled: true  #没有这个ribbon超时不会生效 ribbon. 是ribbon.http.client.enabled的替代品
  ReadTimeout: 1000
  ConnectTimeout: 1000
  MaxAutoRetries: 1 #同一台实例最大重试次数,不包括首次调用
  MaxAutoRetriesNextServer: 1 #重试负载均衡其他的实例最大重试次数,不包括首次调用
  #当OkToRetryOnAllOperations设置为false时,只会对get请求进行重试。
  #如果设置为true,便会对所有的请求进行重试,如果是put或post等写操作,
  #如果服务器接口没做幂等性,会产生不好的结果,所以OkToRetryOnAllOperations慎用。
  OkToRetryOnAllOperations: false  #是否所有操作都重试

具体为什么要设置ribbon.http.client.enabled 请参考Ribbon、Feign、Hystrix和Zuul超时重试设置(一)Spring Cloud Ribbon的踩坑记录与原理详析

3.类的配置及调用方式

启动类

@SpringBootApplication
@EnableDiscoveryClient
public class ConsumerRibbonApplication {
    public static void main(String[] args) {
        SpringApplication.run(ConsumerRibbonApplication.class, args);
    }
}

配置类

@Configuration
public class CommonConfig {

  //方式一
    @Bean
    @LoadBalanced
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
    //方式二
    /*@Bean
    @LoadBalanced
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        return builder.build();
    }*/

    // 自定义负载均衡策略
   /*  
    @Bean
    public IRule ribbonRule() {
        return new MyRule();
    }*/
}

自定义负载均衡规则配置类(自定义的时候用到,默认是轮询)

需要extends AbstractLoadBalancerRule,下面的规则是,每个服务实例执行5次
参考SpringCloud-Ribbon(自定义负载均衡算法), Spring Cloud:自定义 Ribbon 负载均衡策略

public class MyRule extends AbstractLoadBalancerRule {
    // total = 0 // 当total==5以后,我们指针才能往下走,
    // index = 0 // 当前对外提供服务的服务器地址,
    // total需要重新置为零,但是已经达到过一个3次,我们的index = 1
    private int total = 0;    // 总共被调用的次数,目前要求每台被调用5次
    private int currentIndex = 0; // 当前提供服务的机器号

    public Server choose(ILoadBalancer lb, Object key)
    {
        if (lb == null) {
            return null;
        }
        Server server = null;
        while (server == null) {
            if (Thread.interrupted()) {
                return null;
            }

            List<Server> upList = lb.getReachableServers();
            List<Server> allList = lb.getAllServers();
            int serverCount = allList.size();
            if (serverCount == 0) {
                return null;
            }
            if(total < 5)
            {
                server = upList.get(currentIndex);
                total++;
            }else {
                total = 0;
                currentIndex++;
                if(currentIndex >= upList.size())
                {
                    currentIndex = 0;
                }
            }
            if (server == null) {
                Thread.yield();
                continue;
            }
            if (server.isAlive()) {
                return (server);
            }
            server = null;
            Thread.yield();
        }
        return server;
    }
    @Override
    public Server choose(Object key)
    {
        return choose(getLoadBalancer(), key);
    }

    @Override
    public void initWithNiwsConfig(IClientConfig clientConfig)
    {
    }
}

service


@Service
public class AccountConsumerService {

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private LoadBalancerClient loadBalancerClient;

    /**
     * 测试负载均衡功能
     *
     * @param i
     */
    public void loadBalancerRun(int i) {
        for (int j = 0; j < i; j++) {
            ServiceInstance choose = loadBalancerClient.choose("account-demo");
            System.out.println("choose.getInstanceId()+\":\"" + choose.getInstanceId());
        }
    }

    /**
     * 测试重试功能
     *
     * @param id
     * @throws Exception
     */
    public void retry(Long id) throws Exception {
        String url = "http://account-demo/account/get/" + id;
        String forObject = restTemplate.getForObject(url, String.class);
        System.out.println("forObject = " + forObject);
    }

}

controller

@RestController
@RequestMapping("consumer")
public class AccountConsumerController {

    @Resource
    private AccountConsumerService accountConsumerService;

    @RequestMapping("balancer/{times}")
    public String balance(@PathVariable int times){
        accountConsumerService.loadBalancerRun(times);
        return "OK !";
    }

    @RequestMapping("retry/{id}")
    public String retry(@PathVariable Long id) throws Exception{
        accountConsumerService.retry(id);
        return "OK !";
    }
}

自定义负载均衡

方式一

account-demo:  #针对的服务名
    ribbon:
       NFLoadBalancerRuleClassName: com.d4c.config.MyRule

上面的配置方法针对account-demo服务会采用MyRule的负载均衡规则。

同理,我想把我的MyRule针对所有服务
以为下面这种配发能起作用,但实际不起作用,还是默认的轮询策略。

ribbon:
  NFLoadBalancerRuleClassName: com.d4c.config.MyRule

于是从网上找来了另一种起作用的方法。

需要定义配置累
或者直接吧MyRule注入到spring(@Componnet)或者

//这种是针对所有服务
@Configuration
public class MyRibbonConfig {
   // 自定义负载均衡策略
    @Bean
    public IRule ribbonRule() {
        return new MyRule();
    }
}

为什么能全局应用,就是把这个自定义文件放到了@ComponentScan所扫描的地方

官方文档给出警告:
这个自定义的类不能放在@ComponentScan所扫描的当前包以及子包下,否则我们自定义的这个配置类就会被所有的Ribbon客户端所共享,也就是我们达不到特殊化指定的目的了。

如果我们把这个配置文件放到@ComponentScan扫描不到的地方,或者说扫描的时候排除这个配置类,那么能不能实现针对服务级别的配置或隔离
下面这种方法就是针对服务的配置
方式二
1.把MyRibbonConfig 放到启动类扫描不到的地方。

image.png
2.或者扫描时排除此配置类。
扫描排除某类的方法 springcloud-04-自定义ribbon的配置方式
package com.ribbon;

import com.d4c.config.MyRule;
import com.netflix.loadbalancer.IRule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyRibbonConfig {

    @Bean
    public IRule ribbonRule(){
        //随机负载
        return new MyRule();
    }
}

配置@RibbonClient 或者@RibbonClients(这个注解放启动类上或项目能自动扫描的地方就行了)

//针对一个服务
@RibbonClient(name = "account-demo", configuration = MyRule.class),
public class RibbonClientConfig {
}


//针对多个服务
@RibbonClients(value = {
        @RibbonClient(name = "account-demo", configuration = MyRule.class),
        @RibbonClient(name = "product-demo2", configuration = RandomRule.class)
},defaultConfiguration = {MyRule.class})
public class RibbonClientsConfig {
}

ribbon的超时配置

ribbon:
  restclient:
    enabled: true  #没有这个ribbon超时不会生效 ribbon. 是ribbon.http.client.enabled的替代品
  ReadTimeout: 1000
  ConnectTimeout: 1000
  MaxAutoRetries: 1 #同一台实例最大重试次数,不包括首次调用
  MaxAutoRetriesNextServer: 1 #重试负载均衡其他的实例最大重试次数,不包括首次调用
  #当OkToRetryOnAllOperations设置为false时,只会对get请求进行重试。
  #如果设置为true,便会对所有的请求进行重试,如果是put或post等写操作,
  #如果服务器接口没做幂等性,会产生不好的结果,所以OkToRetryOnAllOperations慎用。
  OkToRetryOnAllOperations: false  #是否所有操作都重试

ribbon的重试

 <dependency>
       <groupId>org.springframework.retry</groupId>
       <artifactId>spring-retry</artifactId>
  </dependency>

配置

spring:
  cloud:
    loadbalancer:
      retry:
        enabled: true # 开启Spring Cloud的重试功能

单独使用Ribbon

因为往往Ribbon配合Eureka使用的,往往也有第三方服务没有注册到Eureka Server,但也部署了多个实例,也需要进行负载均衡,这时可以在服务消费者的配置文件中进行如下方式配置,实现负载均衡

#取消Ribbon使用Eureka
ribbon:
  eureka:
   enabled: false
#配置Ribbon能访问 的微服务节点,多个节点用逗号隔开
account-demo:
   ribbon:
      listOfServers:localhost:6060,localhost:6070

参考 spring cloud各种超时时间及重试设置

上一篇下一篇

猜你喜欢

热点阅读