SpringCloud(5)-Ribbon

SpringCloud(5)-Ribbon

Introduction to Ribbon

  • Spring Cloud Ribbon is a set of client load balancing tools based on Netflix Ribbon .
  • Simply put, Ribbon is an open source project released by Netflix. Its main function is to provide a software load balancing algorithm for clients and connect Netflix's middle-tier services together. The client component of Ribbon provides a series of complete configuration items such as: connection timeout, retry, etc. Simply put, it is to list all the machines behind LoadBalancer (abbreviated as LB: load balancing) in the configuration file. Ribbon will automatically help you connect these machines based on certain rules (such as simple polling, random connection, etc.). We are also very easy to use Ribbon to implement a custom load balancing algorithm!

Load Balance

  • LB, or Load Balance, is an application often used in microservices or distributed clusters.

  • Load balancing simply means that the user's request is evenly distributed to multiple services, so as to achieve the HA (high availability) of the system.

  • Common load balancing software includes Nginx, Lvs and so on.

  • Dubbo and SpringCloud both provide us with load balancing. SpringCloud's load balancing algorithm can be customized.

  • Simple classification of load balancing:

    1. Centralized LB

    That is to use an independent LB facility between the consumer and provider of the service, such as Nginx (reverse proxy server), which is responsible for forwarding the access request to the service provider through a certain strategy!

    1. Progressive LB

    Integrate the LB logic into the consumer, the consumer knows which addresses are available from the service registration center, and then chooses a suitable server from these addresses. Ribbon belongs to the process LB, it is just a class library, integrated in the consumer process, the consumer obtains the address of the service provider through it!

Integrate Ribbon

  1. Add the Ribbon dependency and Eureka dependency to the pom file of the original client springcloud-consumer-dept-80 project
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
  1. Configure Eureka in application.yml
eureka:
  instance:
    hostname: localhost #eureka服务端实例名称
  client:
    register-with-eureka: false #表示是否向eureka注册自己
    fetch-registry: false #如果为false表示自己为注册中心
    service-url:  #监控页面
      defaultZone: http://127.0.0.1:7001/eureka/,http://127.0.0.1:7002/eureka/,http://127.0.0.1:7003/eureka/
  1. Start EurekaClient on the main startup class
@EnableEurekaClient
@SpringBootApplication
public class DeptConsumer_80 {
    public static void main(String[] args) {
        SpringApplication.run(DeptConsumer_80.class,args);
    }
}
  1. Modify the original BeanConfig
//配置负载均衡实现RestTemplate
@Bean
@LoadBalanced //Ribbon
public RestTemplate restTemplate(){
    return new RestTemplate();
}
  1. Modify the original REST_PATH_PREFIX in DeptConsumerController to application name, and visit based on the service name. The client does not need to care about the IP address and port number of the service provider! (Originally: private static final String REST_PATH_PREFIX = " http: // localhost: 8001 ")
private static final String REST_PATH_PREFIX="http://springcloud-provider-dept";
  1. Start the project, visit http: // localhost / consumer / dept / all to test:

Ribbon to achieve load balancing

  1. Create two new databases sc02, sc03, the data is the same as sc01 except db_source.

  2. Create two new Maven projects springcloud-provider-dept-8002 and springcloud-provider-dept-8003. Copy everything in the springcloud-provider-dept-8001 project.

  3. Modify the port number in springcloud-provider-dept-8002, springcloud-provider-dept-8003 application.yml, the connected database name and Eureka's default description information.

  4. Ensure that the application names of the three service providers are the same.

spring:
  application:
    name: springcloud-provider-dept
  1. Remember to modify the dept table in the mapper to query the corresponding database.
  2. Write the corresponding startup class.
  3. Start the project and visit http: // localhost: 7001 /:

Visit http: // localhost / consumer / dept / all, refresh the page many times, and find that different databases are queried (the default algorithm is simple polling):

Custom load balancing algorithm

  1. Select the service consumer springcloud-consumer-dept-80, create a new package myrule under the com.yinrz package, and write a custom load balancing algorithm class MyRule:
//自定义负载均衡算法:一个服务连续访问5次后,换下一个服务
public class MyRule extends AbstractLoadBalancerRule {
    public MyRule(){
    }
    private int total=0;
    private int current=0;

    @SuppressWarnings({"RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE"})
    public Server choose(ILoadBalancer lb, Object key) {



        if (lb == null) {
            return null;
        } else {
            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;
                }

//========================核心算法开始==============================
                System.out.println(111);
                if(total<=5){
                    server = upList.get(current);
                    total++;
                }else {
                    total=0;
                    current++;
                    if (current>=upList.size()){
                        current=0;
                    }
                    server = upList.get(current);
                }

//========================核心算法结束==============================


                if (server == null) {
                    Thread.yield();
                } else {
                    if (server.isAlive()) {
                        return server;
                    }

                    server = null;
                    Thread.yield();
                }
            }

            return server;
        }
    }

    protected int chooseRandomInt(int serverCount) {
        return ThreadLocalRandom.current().nextInt(serverCount);
    }

    @Override
    public Server choose(Object key) {
        return this.choose(this.getLoadBalancer(), key);
    }

    @Override
    public void initWithNiwsConfig(IClientConfig clientConfig) {
    }

}
  1. Write a configuration class MyRuleConfig under the myrule package:
@Configuration
public class MyRuleConfig {

    @Bean
    public IRule myRule(){
        return new MyRule();
    }
}
  1. Add annotation @RibbonClient on the main startup class:
@EnableEurekaClient
@SpringBootApplication
@RibbonClient(name = "springcloud-provider-dept",configuration = MyRuleConfig.class)//在微服务启动的时候就能加载我们自定义的Ribbon类
public class DeptConsumer_80 {
    public static void main(String[] args) {
        SpringApplication.run(DeptConsumer_80.class,args);
    }
}
  1. Run 3 service providers, Eureka server, service consumer project, visit http: // localhost / consumer / dept / all to test.

Guess you like

Origin www.cnblogs.com/yinrz/p/12755734.html