5、springcloud之客戶端負載均衡Ribbon

1、簡介

  在微服務架構中,業務都會被拆分紅一個獨立的服務,服務與服務的通信是基於http restful的。Spring cloud有兩種服務調用方式:web

    一種是ribbon+restTemplatespring

    另外一種是feignrestful

  ribbon是一個負載均衡客戶端,能夠很好的控制htt和tcp的一些行爲。Feign默認集成了ribbon架構

  ribbon核心組件有三個負載均衡

    • Rule - 從服務列表中如何獲取一個有效服務
    • Ping - 後臺運行線程用來判斷服務是否可用
    • ServerList - 服務列表

2、準備

  1.服務註冊中心tcp

  2.服務提供方:多個serviceide

3、使用Ribbon實現客戶端負載均衡的消費者

  1.pom.xmlspring-boot

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.3.5.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-ribbon</artifactId>
    </dependency>
    <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.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

<dependencyManagement>
    <dependencies>
        <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-dependencies</artifactId>
        <version>Brixton.RELEASE</version>
        <type>pom</type>
        <scope>import</scope>
    </dependency>
    </dependencies>
</dependencyManagement>
View Code

  2.@EnableDiscoveryClient註解來添加發現服務能力微服務

  3.經過@LoadBalanced註解代表這個restRemplate開啓負載均衡的功能。spa

   RestTemplate 構建RestTemplate對應的bean,在method上使用註解@LoadBalanced表示restTemplate使用LoadBalancerClient執行請求

@Configuration
public class RibbonConfig {
    /**
     * LoadBalanced 註解代表restTemplate使用LoadBalancerClient執行請求
     */
    @Bean
    @LoadBalanced
    public RestTemplate restTemplate() {
        RestTemplate template = new RestTemplate();
        SimpleClientHttpRequestFactory factory = (SimpleClientHttpRequestFactory) template.getRequestFactory();
        factory.setConnectTimeout(3000);
        factory.setReadTimeout(3000);
        return template;
    }
}

  4.controller直接注入resttemplate,調用服務,便可

注:若是使用了feign,Feign默認集成了ribbon,無須任何配置,調用服務,請求會自動輪詢到每一個服務端來處理。

相關文章
相關標籤/搜索