1. 程式人生 > >SpringCloud——使用Ribbon做負載均衡

SpringCloud——使用Ribbon做負載均衡

Ribbon負載均衡

一、簡介

1:什麼是負載均衡

負載均衡建立在現有網路結構之上,它提供了一種廉價有效透明的方法擴充套件網路裝置和伺服器的頻寬、增加吞吐量、加強網路資料處理能力、提高網路的靈活性和可用性。

負載均衡(Load Balance)其意思就是分攤到多個操作單元上進行執行,例如Web伺服器、FTP伺服器、企業關鍵應用伺服器和其它關鍵任務伺服器等,從而共同完成工作任務。以上內容來自於百度百科

個人理解而言,負載均衡,是彌補了單體架構或者單個服務的負載能力不足而導致的整體效能瓶頸,因此,可以通過將一個服務部署多臺伺服器,然後將一臺機器原來的壓力分攤到多個執行單元上,這樣就提升了原有架構的效能瓶頸。可以理解為 “將負載均衡到多個服務中”。常見的負載均衡有兩種策略:

  • Nginx獨立程序做負載均衡,通過負載均衡策略,將請求轉發到不同的執行單元上
  • 客戶端負載均衡策略,通過在客戶端儲存服務列表資訊,然後自己呼叫負載均衡策略,分攤呼叫不同的執行單元。

2:什麼是Ribbon

Ribbon是Netflix公司開源的一個負載均衡的元件,它屬於上述負載均衡方式中的第二種。將負載均衡的邏輯封裝在了客戶端中,並且執行在客戶端。Ribbon經過了非常嚴格的測試,可以更好的控制Http和Tcp客戶端的負載均衡行為。

Ribbon的負載均衡有兩種方式

  1. 和RestTemplate結合
  2. 和Feign結合

Ribbon的核心子模組

  1. ribbon-loadbalancer:可以獨立使用或者和其他模組一起使用的負載均衡API
  2. ribbon-eureka:結合Eureka作客戶端的API
  3. ribbon-core:Ribbon的核心API

3:什麼是RestTemplate

RestTemplate是SpringResource中一個訪問第三方RESTful API介面的網路通訊框架。其主要方法都與REST的HTTP協議的方法緊密關聯。 RestTemplate支援常見的HTTP請求方式,例如GET、POST、PUT、DELETE等,所以RestTemplate很容易構建RESTful API 呼叫方式例如

restTemplate.getForObject("http://common-service/hello", String.class)

其核心API如下
https://docs.spring.io/spring/docs/3.0.x/javadoc-api/org/springframework/web/client/RestTemplate.html

二、開始使用Ribbon

Ⅰ.程式碼編寫

  1. ribbon-test父專案
  • pom.xml
<groupId>com.calvin.ribbon</groupId>
 <artifactId>ribbon-test</artifactId>
 <packaging>pom</packaging>
 <version>1.0-SNAPSHOT</version>

 <modules>
     <module>common-service</module>
     <module>eureka-server</module>
     <module>ribbon-service</module>
 </modules>

 <parent>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-parent</artifactId>
     <version>1.5.3.RELEASE</version>
 </parent>

 <properties>
     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
     <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
     <java.version>1.8</java.version>
 </properties>

 <dependencyManagement>
     <dependencies>
         <dependency>
             <groupId>org.springframework.cloud</groupId>
             <artifactId>spring-cloud-dependencies</artifactId>
            <version>Dalston.SR4</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>
  1. eureka-server
  • pom.xml
<parent>
    <groupId>com.calvin.ribbon</groupId>
    <artifactId>ribbon-test</artifactId>
    <version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>eureka-server</artifactId>
<properties>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-eureka-server</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

application.yml

server:
  port: 8080
eureka:
  instance:
    hostname: localhost
  client:
    register-with-eureka: false
    fetch-registry: false
    service-url:
      defaultZone:
        http://${eureka.instance.hostname}:${server.port}/eureka

  • ServerApplication.java
@EnableEurekaServer
@SpringBootApplication
public class ServerApplication {

    public static void main(String[] args) {
        SpringApplication.run(ServerApplication.class);
    }
}
  1. commons-service
  • pom.xml
<parent>
    <artifactId>ribbon-test</artifactId>
    <groupId>com.calvin.ribbon</groupId>
    <version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>

<artifactId>common-service</artifactId>

<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-eureka</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
  • application.yml
spring:
  application:
    name: common-service

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8080/eureka/

此處沒有指定server.port,是因為我們在啟動此服務的是時候做點手腳,需要以不同埠在本地啟動, 即配置兩個Name不同的啟動類,給分別指定不同的Environment variables,內容為server.port=8083, server.port=8084 具體教程是在Idea下的EditConfiguration中做如下操作:

  • CommonServiceApplication.java
@SpringBootApplication
@EnableEurekaClient
public class CommonServiceApplication {

    public static void main(String[] args) {
        SpringApplication.run(CommonServiceApplication.class);
    }
}
  • HelloController.java
@RestController
public class HelloController {

    @Value("${server.port}")
    private String port;

    /**
     * 介面測試
     * @return
     */
    @GetMapping("/hello")
    public String sayHello(){
        return "port : " + port ;
    }
}

  1. ribbon-service
  • pom.xml
<parent>
    <artifactId>ribbon-test</artifactId>
    <groupId>com.calvin.ribbon</groupId>
    <version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>ribbon-service</artifactId>
<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-eureka</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-ribbon</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
  • application.yml
server:
  port: 8082
spring:
  application:
    name: ribbon-service

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8080/eureka/
  • RibbonClientApplication.java
@EnableEurekaClient
@SpringBootApplication
public class RibbonServerApplication {

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

    /**
     * 配置LoadBalance和RestTemplate
     * @return RestTemplate
     */
    @Bean
    @LoadBalanced
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }

}

接下來就是呼叫的關鍵程式碼

  • RemoteCommonService.java
/**
 * <p> 
 *	CommonService服務遠端呼叫類
 * </p>
 * @author Calvin
 * @date 2019/10/09
 * @since 1.0
 */
@Service
public class RemoteCommonService {

    /**
     * 注入RestTemplate
     */
    @Autowired
    private RestTemplate restTemplate;

    /**
     * 遠端呼叫common-service/hello
     * @return
     */
    public String sayHi(){
        return restTemplate.getForObject("http://common-service/hello", String.class);
    }

}

  • SayHiController.java
@RestController
public class SayHiController {


    @Autowired
    private RemoteCommonService remoteCommonService;

    @GetMapping("hi")
    public String sayHi(){
        return remoteCommonService.sayHi() + ", this is ribbon service";
    }

}

Ⅱ.配置啟動

最終配置四個啟動類,如圖所示:

啟動順序:

  • step1. EurekaSeverApplicaton
  • step2. CommonServiceApplication
  • step3. CommonServiceApplication2
  • step4. RibbonServerApplication

Ⅲ.結果驗證

Eureka管理介面 http://localhost:8080/

呼叫 http://localhost:8082/hi

重新整理頁面

三、核心剖析——LoadBalancerClient

負載均衡的核心類是LoadBalanceClient,此類可以獲取負載均衡的服務提供者的例項資訊,當然這些例項資訊是通過EurekaClient獲取的,並且快取了一份服務例項資訊。

@Autowired
    private LoadBalancerClient loanBalanceClient;

    /**
     * 遠端呼叫common-service/hello
     * @return
     */
    public String sayHi(){
        ServiceInstance serviceInstance = loanBalanceClient.choose("common-service");
        logger.info("current service info is {} : {}", serviceInstance.getHost(), serviceInstance.getPort());
        return restTemplate.getForObject("http://common-service/hello", String.class);
    }

此時不斷刷介面,同樣可以看到LoadBalancerClient在不斷的改變請求的例項資訊。

四、小結

  1. 認識了關於Ribbon以及常用負載均衡的概念
  2. 動手實踐了一下Ribbon進行負載均衡的呼叫
  3. 認識Ribbon的一個核心類

五、總結

  1. 本文首次實踐Ribbon做負載均衡,缺乏原理剖析
  2. 文章中程式碼相對簡單,但是基本可以表達Ribbon所做的事情
  3. 需要在以後,對整個Ribbon的原始碼進行解析(算是插眼)
  4. 關於RestTemplate還有很多用法,後續可以專門出文章進