介紹客戶端負載均衡Spring Cloud Ribbon

Spring Cloud Ribbon是一個基于HTTP和TCP的客戶端負載均衡工具,它基于Netflix Ribbon實現。可輕松地將面向服務的REST請求自動轉換成客戶端負載均衡的服務調用。Netflix Ribbon是一個在云端使用的IPC(進程間通信)庫,主要提供客戶端的負載均衡算法。

除了客戶端負載均衡算法,Ribbon還提供其他功能:

  • 服務發現集成 - Ribbon負載均衡器可在動態環境(如云)中提供服務發現功能。與Eureka和Netflix服務發現組件的集成包含在Ribbon庫中。
  • 容錯 - Ribbon API可以動態確定服務是否在工作環境中運行,并且可以檢測到服務器是否停機。
  • 可配置的負載均衡規則 - Ribbon支持RoundRobinRule,AvailabilityFilteringRule,WeightedResponseTimeRule等開箱即用的規則,并且還支持自定義規則。

下面通過一個簡單的例子介紹Ribbon是如何使用的。在本例中我們創建一個簡單的微服務應用,使用Spring RestTemplate去調用服務提供者的服務,并配合Ribbon API實現負載均衡。服務提供方啟動2個服務實例,使用WeightedResponseTimeRule負載均衡策略,在配置文件中指定服務列表。通過服務名的方式實現在2個服務實例間的負載。

1 依賴管理

在pom.xml里增加依賴庫

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-ribbon</artifactId>
</dependency>

2 Ribbon配置

Ribbon API支持下面這些內容的配置

  • Rule — 邏輯組件,指定我們在應用程序中使用的負載均衡規則。
  • Ping — 一個組件,它指定了用于實時確定服務器可用性的機制。
  • ServerList — 可以是動態或靜態的。在我們的例子中,我們使用的是一個靜態的服務器列表,我們直接在應用程序配置文件中定義了它們。
    下面是配置類
public class RibbonConfiguration {
    @Autowired
    IClientConfig ribbonClientConfig;

    // 判斷服務實例是否有效,ping某個url判斷其是否alive
    @Bean
    public IPing ribbonPing(IClientConfig config) {
        return new PingUrl();
    }

    // 負載均衡策略,根據服務實例的運行情況來計算權重
    @Bean
    public IRule ribbonRule(IClientConfig config) {
        return new WeightedResponseTimeRule();
    }
}

3 配置文件

application.yml

spring:
  application:
    name: spring-cloud-ribbon

server:
  port: 8888

ping-server:
  ribbon:
    eureka:
      enabled: false
    listOfServers: localhost:8081,localhost:8082
    ServerListRefreshInterval: 15000

在上面的文件中定義了

  • 應用的名稱
  • 應用的端口
  • 服務列表的名稱:ping-server
  • 禁用 eureka服務發現組件,不把此客戶端發布為服務
  • 定義了用于負載平衡的服務器列表,在這里有2個服務器
  • 配置服務器的刷新頻率

4 RibbonClient

現在實現Ribbon客戶端

@SpringBootApplication
@RestController
@RibbonClient(name = "ping-a-server", configuration = RibbonConfiguration.class)
public class ServerLocationApp {

    @LoadBalanced
    @Bean
    RestTemplate getRestTemplate() {
        return new RestTemplate();
    }

    @Autowired
    RestTemplate restTemplate;

    @RequestMapping("/server-location")
    public String serverLocation() {
        String servLoc = this.restTemplate.getForObject("http://ping-server/locate", String.class);
        return servLoc;
    }

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

我們定義了一個Controller類通過@RestController注解并添加了@RibbonClient注解。注解里的配置就是前面定義的配置類,在這個類中我們為這個應用程序提供了所需的Ribbon API配置。需注意的是在RestTemplate上使用了@LoadBalanced注解表示使用RestTemplate去調用服務時進行負載均衡。

5 服務提供者

一個簡單的定位服務。

@Configuration
@EnableAutoConfiguration
@RestController
public class TestServiceProvider {

    @RequestMapping(value = "/locate")
    public String locationDetails() {
        return "Beijing";
    }
}

6 測試

通過一個測試用例啟動2個服務實例,然后調用RibbonClient得到定位信息。

@SuppressWarnings("unused")
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ServerLocationApp.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ServerLocationAppIntegrationTest {
    ConfigurableApplicationContext application2;
    ConfigurableApplicationContext application3;

    @Before
    public void startApps() {
        this.application2 = startApp(8081);
        this.application3 = startApp(8082);
    }

    @After
    public void closeApps() {
        this.application2.close();
        this.application3.close();
    }

    @LocalServerPort
    private int port;

    @Autowired
    private TestRestTemplate testRestTemplate;

    @Test
    public void loadBalancingServersTest() throws InterruptedException {
        // 調用Ribbon客戶端
        ResponseEntity<String> response = this.testRestTemplate
                .getForEntity("http://localhost:" + this.port + "/server-location", String.class);
        assertEquals(response.getBody(), "Beijing");
    }

    // 啟動服務實例
    private ConfigurableApplicationContext startApp(int port) {
        return SpringApplication.run(TestServiceProvider.class, "--server.port=" + port, "--spring.jmx.enabled=false");
    }
}

7 總結

在本文中我們介紹了Ribbon API并通過一個簡單的應用說明了它是如何實現的。Ribbon API不僅提供了客戶端負載均衡算法還內置了一些容錯保護,如前所述它可以通過不斷的ping服務器來確定服務器的可用性和排除掉不能提供服務的服務器。除此之外,它還實現了斷路器模式,根據指定的標準過濾服務器。斷路器模式不用等待超時而迅速拒絕請求失敗的服務器的請求,從而最大限度地減少服務器故障對性能的影響。

本例中的代碼可以在 GitHub repository 中找到。

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容