1. 程式人生 > 實用技巧 >Spring04-Ribbon :負載均衡

Spring04-Ribbon :負載均衡

Ribbon :負載均衡

負載均衡

分散式系統中,客戶端需要呼叫提供者,提供者在多型註冊中心中存在,客戶端任意呼叫一個伺服器均可以完成;為了使每一臺註冊中心不用太忙也不要太閒,可以負載均衡呼叫每一臺註冊中心,可以提升網站的健壯性。

常見的負載均衡的演算法

  • 輪詢:為第一個請求選擇正常執行中的註冊中心的第一臺服務(註冊中心),然後按順序依次往後選擇,直到最後一個,然後迴圈
  • 最小連線:優先選擇連線數最小的,即壓力最小的後端伺服器;在會話較長情況下可以考慮此方法。
  • 雜湊:根據請求源的ip的雜湊(hash)來選擇要轉發的伺服器;這種方法可以在一定程度上保證特定使用者能連線到相同的伺服器。

整合ribbon(以客戶端的形式)

​ 1)匯入依賴,之後還要從服務中心獲取資訊,所以Eureka的依賴也需要(客戶端的Eureka)

<!--Ribbon-->
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-ribbon -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-ribbon</artifactId>
    <version>1.4.6.RELEASE</version>
</dependency>
  <!--Eureka-->
 <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-eureka -->
<dependency>
     <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-eureka</artifactId>
        <version>1.4.6.RELEASE</version>
  </dependency>

​ 2)編寫配置

server:
  port: 80


#Eureka配置
eureka:
  client:
    register-with-eureka: false    #不向eureka註冊自己(我們是去拿資訊)
    service-url:    #可以從這三個註冊中心拿
      defaultZone: http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/,http://eureka7001.com:7001/eureka/

​ 3)讓Eureka生效

/**
 * Ribbon 和 Eureka 整合以後,客戶端可以直接呼叫,不用關心IP地址和埠號
 */
@SpringBootApplication
@EnableEurekaClient  //Eureka客戶端
public class DeptConsumer_80 {
    public static void main(String[] args) {
        SpringApplication.run(DeptConsumer_80.class,args);
    }
}

4)配置負載均衡實現restTemplate

@Configuration    //@Configuration 相當於spring裡面的 applicationContext.xml
public class ConfigBean {
    //配置負載均衡實現RestTemplate
    @Bean
    @LoadBalanced   //Ribbon
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }
}  

​ 通過Ribbon去實現負載均衡的時候,controller裡的跳轉地址應該是一個變數(即服務提供者的id),之後啟動就可以了

//Ribbon,我們這裡的地址,應該是一個變數,通過服務名來訪問
//private static final String REST_URL_PERFIx="http://localhost:8001";
private static final String REST_URL_PERFIx="http://SPRINGCLOUD-PRIVIDER-DEPT";

以上是隻用了一個數據庫,我們也可使用多個數據試一下,有多個數據庫的情況下,Ribbon會使用演算法負載均衡,以便算出要訪問那個資料庫。如下圖