【Spring Cloud】005-Ribbon负载均衡

一、负载均衡与Ribbon

1、Ribbon是什么

Spring Cloud Ribbon 是基于Netflix Ribbon 实现的一套客户端负载均衡的工具

简单的说,Ribbon 是 Netflix 发布的开源项目,主要功能是提供客户端的软件负载均衡算法,将 Netflix 的中间层服务连接在一起。Ribbon 的客户端组件提供一系列完整的配置项,如:连接超时、重试等。简单的说,就是在配置文件中列出 LoadBalancer (简称LB:负载均衡) 后面所有的及其,Ribbon 会自动的帮助你基于某种规则 (如简单轮询,随机连接等等) 去连接这些机器。我们也容易使用 Ribbon 实现自定义的负载均衡算法;

 

2、Ribbon能干嘛

LB,即负载均衡 (LoadBalancer) ,在微服务或分布式集群中经常用的一种应用;

负载均衡简单的说就是将用户的请求平摊的分配到多个服务上,从而达到系统的HA (高用);

常见的负载均衡软件有 Nginx、Lvs 等等;

Dubbo、SpringCloud 中均给我们提供了负载均衡,SpringCloud 的负载均衡算法可以自定义

 

负载均衡简单分类:

集中式LB:

即在服务的提供方和消费方之间使用独立的LB设施,如Nginx,由该设施负责把访问请求通过某种策略转发至服务的提供方;

进程式LB:

将LB逻辑集成到消费方,消费方从服务注册中心获知有哪些地址可用,然后自己再从这些地址中选出一个合适的服务器;

Ribbon 就属于进程内LB,它只是一个类库,集成于消费方进程,消费方通过它来获取到服务提供方的地址;

 

二、集成Ribbon

1、在客户端springcloud-consumer-dept-80导入Ribbon依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>springcloud</artifactId>
        <groupId>com.zibo</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>springcloud-consumer-dept-80</artifactId>
    <!--实体类 + web-->
    <dependencies>
        <!--集成Ribbon-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-ribbon</artifactId>
            <version>1.4.7.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
            <version>1.4.7.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>com.zibo</groupId>
            <artifactId>springcloud-api</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--热部署工具-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
    </dependencies>

</project>

 

2、编写配置

server:
  port: 80

# Eureka配置
eureka:
  client:
    register-with-eureka: false # 不向eureka注册自己
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/

 

3、在主启动类添加注解,开启功能

package com.zibo.springcloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

@SpringBootApplication
@EnableEurekaClient //自动在服务启动后自动注册到Eureka中
public class DeptConsumer_80 {
    public static void main(String[] args) {
        SpringApplication.run(DeptConsumer_80.class,args);
    }
}

 

4、修改配置类

package com.zibo.springcloud.config;

import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class ConfigBean {

    //配置负载均衡实现RestTemplate
    @Bean
    @LoadBalanced //Ribbon
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }

}

 

5、修改ConsumerDeptController

package com.zibo.springcloud.controller;

import com.zibo.springcloud.pojo.Dept;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
public class ConsumerDeptController {

    //理解:消费者,不应该有service层
    //RestTemplate 供我们直接调用就可以了!注册到Spring中
    //参数:(url,实体:Map,class<T> responseType,)
    @Autowired
    private RestTemplate restTemplate;//提供多种便捷访问远程http服务的方法,简单的Restful服务模板

    //private static final String REST_URL_PRE = "http://localhost:8001";
    //Ribbon 我们使用负载均衡之后,这里的地址应该是一个变量,通过服务名来访问
    private static final String REST_URL_PRE = "http://SPRINGCLOUD-PROVIDER-DEPT";

    //http://localhost:8001/dept/get/1
    @RequestMapping("/consumer/dept/get/{id}")
    public Dept getById(@PathVariable("id") long  id){
        return restTemplate.getForObject(REST_URL_PRE + "/dept/get/" + id,Dept.class);
    }

    @RequestMapping("/consumer/dept/add")
    public boolean add(Dept dept){
        return restTemplate.postForObject(REST_URL_PRE + "/dept/add",dept,Boolean.class);
    }

    @RequestMapping("/consumer/dept/get")
    public List<Dept> get(){
        return restTemplate.getForObject(REST_URL_PRE + "/dept/get",List.class);
    }

}

 

6、测试

分别启动三台服务器、服务提供方、服务消费方;

启动:

访问:

 

7、结论

Ribbon和Enreka整合之后,客户端可以直接调用,不用关心IP地址和端口号;

 

三、使用Ribbon实现负载均衡

1、说明

我们之前只有一个服务springcloud-provider-dept-8001,怎么访问使用的都是这一个服务,无法实现负载均衡,让我们再创建两个服务,实现负载均衡;

 

2、新增两个数据库

 

3、新增两个服务

springcloud-provider-dept-8002和springcloud-provider-dept-8003

说明:

yaml配置文件示例:

server:
  port: 8002

# mybatis配置
mybatis:
  type-aliases-package: com.zibo.springcloud.pojo
  config-location: classpath:mybatis/mybatis-config.xml
  mapper-locations: classpath:mybatis/mapper/*.xml

# spring配置
spring:
  application:
    name: springcloud-provider-dept
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource #数据源
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/zb2?serverTimezone=UTC
    username: root
    password: zibo15239417242

# Eureka的配置,服务注册到哪里
eureka:
  client:
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
  instance:
    instance-id: springcloud-provider-dept8002 # 修改eureka的默认描述信息

# info配置信息
info:
  app.name: zibo-springcloud
  company.name: com.zibo

 

4、启动测试

启动:


访问:

轮询(默认),这就是传说中的负载均衡!

 

四、自定义负载均衡算法

1、负载均衡算法

  • RoundRobinRule:轮询(默认);
  • AvailabilityFilteringRule:先过滤到跳闸、访问故障的服务,再对剩下的进行轮询;
  • RandomRule:随机;
  • WeightedResponseTimeRule:权重;
  • RetryRule:先按轮询,如果服务获取失败,则在指定的时间内进行重试;

 

2、将负载均衡算法设置为RandomRule随机

说明:

(注意RandomRule写成了RoundRobinRule,代码里面已更正)

代码:

package com.zibo.springcloud.config;

import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RoundRobinRule;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class ConfigBean {

    //配置负载均衡实现RestTemplate
    //IRule
    //RoundRobinRule:轮询(默认)
    //AvailabilityFilteringRule:先过滤到跳闸、访问故障的服务,再对剩下的进行轮询!
    //RandomRule:随机
    //WeightedResponseTimeRule:权重
    //RetryRule:先按轮询,如果服务获取失败,则在指定的时间内进行重试
    @Bean
    @LoadBalanced //Ribbon
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }

    //将负载均衡算法设置为RandomRule随机
    @Bean
    public IRule myRule(){
        return new RandomRule();
    }

}

测试:

 

3、自定义负载均衡算法

创建ZiBoRule类:

package com.zibo.myRule;

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

@Configuration
public class ZiBoRule {
    //将负载均衡算法设置为RandomRule随机
    @Bean
    public IRule myRule(){
        return new MyRule();
    }
}

修改主启动类:

package com.zibo.springcloud;

import com.zibo.myRule.ZiBoRule;
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 //自动在服务启动后自动注册到Eureka中
//在微服务启动的时候,就能去加载我们自定义的Ribbon类
@RibbonClient(name = "SPRINGCLOUD-PROVIDER-DEPT",configuration = ZiBoRule.class)//Application负载均衡的名字
public class DeptConsumer_80 {
    public static void main(String[] args) {
        SpringApplication.run(DeptConsumer_80.class,args);
    }
}

自定义负载均衡算法:

(模仿随机访问写的)

package com.zibo.myRule;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;

import java.util.List;

public class MyRule extends AbstractLoadBalancerRule {

    //每个服务访问3次,换下一个服务(3个)
    //total=0总数,如果等于2,我们指向下一个服务节点
    //index=0,如果total=2,index++
    //轮询:每个服务走三次,下一个

    private int total = 0,index = 0;

    //@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE")
    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;
            }

//            int index = chooseRandomInt(serverCount);//生成区间随机数
//            server = upList.get(index);//从活着的服务中随机获取一个服务

            if(total<3){
                //取当前服务
                if (index >= upList.size()) {
                    index = 0;
                }
                server = upList.get(index);//取当前服务
                total++;
            }else {
                //访问三次之后变成0
                total = 0;
                //访问的第几个服务往后移一个
                index ++;
            }


            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) {
		// TODO Auto-generated method stub
		
	}
}

运行测试:

文件位置图:

备注:

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值