5.使用Ribbon實現客戶端側負載均衡

                            Ribbon實現客戶端側負載均衡

5.1. Ribbon簡介

           Ribbon是Netflix發佈的開源項目,主要功能是提供客戶端的軟件負載均衡算法,將Netflix的中間層服務鏈接在一塊兒。

          Ribbon客戶端組件提供一系列完善的配置項如鏈接超時,重試等。簡單的說,就是在配置文件中列出Load Balancer

          後面全部的機器,Ribbon會自動的幫助你基於某種規則(如簡單輪詢,隨機鏈接等)去鏈接這些機器。咱們也很容易

          使用Ribbon實現自定義的負載均衡算法。簡單地說,Ribbon是一個客戶端負載均衡器。

          Ribbon工做時分爲兩步:

               第一步先選擇 Eureka Server, 它優先選擇在同一個Zone且負載較少的Server;

               第二步再根據用戶指定的策略,在從Server取到的服務註冊列表中選擇一個地址。其中Ribbon提供了多種策略,例如輪詢、隨機、根據響應時間加權等。

5.2. 爲服務消費者整合Ribbon

 pom.xml

<?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">
    <modelVersion>4.0.0</modelVersion>

    <artifactId>microservice-consumer-movie-ribbon</artifactId>
    <packaging>jar</packaging>

    <parent>
        <groupId>com.itmuch.cloud</groupId>
        <artifactId>microservice-spring-cloud</artifactId>
        <version>0.0.1-SNAPSHOT</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>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</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-actuator</artifactId>
        </dependency>
    </dependencies>
</project>

實體類

package com.itmuch.cloud.entity;

import java.math.BigDecimal;

public class User {
  private Long id;

  private String username;

  private String name;

  private Short age;

  private BigDecimal balance;

  public Long getId() {
    return this.id;
  }

  public void setId(Long id) {
    this.id = id;
  }

  public String getUsername() {
    return this.username;
  }

  public void setUsername(String username) {
    this.username = username;
  }

  public String getName() {
    return this.name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public Short getAge() {
    return this.age;
  }

  public void setAge(Short age) {
    this.age = age;
  }

  public BigDecimal getBalance() {
    return this.balance;
  }

  public void setBalance(BigDecimal balance) {
    this.balance = balance;
  }

}

Controller類

package com.itmuch.cloud.controller;

import org.springframework.beans.factory.annotation.Autowired;
 
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.itmuch.cloud.entity.User;

@RestController
public class MovieController {
  @Autowired
  private RestTemplate restTemplate;

  @GetMapping("/movie/{id}")
  public User findById(@PathVariable Long id) {
     
    return this.restTemplate.getForObject("http://microservice-provider-user/simple/" + id, User.class);
  }
 
}

啓動類

package com.itmuch.cloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.FilterType;
import org.springframework.web.client.RestTemplate;

 

@SpringBootApplication
@EnableEurekaClient
public class RibbonApplication {

  @Bean
  @LoadBalanced
  public RestTemplate restTemplate() {
    return new RestTemplate();
  }

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

配置文件

spring:
  application:
    name: microservice-consumer-movie-ribbon
server:
  port: 8010
eureka:
  client:
    healthcheck:
      enabled: true
    serviceUrl:
      defaultZone: http://user:password123@localhost:8761/eureka
  instance:
    prefer-ip-address: true

訪問路徑:

5.3. 使用Java代碼自定義Ribbon配置

 Spring Cloud還容許經過使用@RibbonClient聲明其餘配置(位於RibbonClientConfiguration之上)來徹底控制客戶端。例:

啓動類java

package com.itmuch.cloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

import com.itmuch.config.TestConfiguration;

 

@SpringBootApplication
@EnableEurekaClient
@RibbonClient(name="microservice-provider-user",configuration=TestConfiguration.class)
public class RibbonApplication {

  @Bean
  @LoadBalanced
  public RestTemplate restTemplate() {
    return new RestTemplate();
  }

  public static void main(String[] args) {
    SpringApplication.run(RibbonApplication.class, args);
  }
}
package com.itmuch.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RandomRule;

@Configuration
public class TestConfiguration {
     @Autowired
     IClientConfig config;
     @Bean
     public IRule ribbonRule(IClientConfig config) {
            return new RandomRule();
     }
}

圖文:web

111--->172.20.10.4:7900:microservice-provider-user
222--->172.20.10.4:7801:microservice-provider-user2
111--->172.20.10.4:7901:microservice-provider-user
222--->172.20.10.4:7800:microservice-provider-user2
111--->172.20.10.4:7900:microservice-provider-user
222--->172.20.10.4:7801:microservice-provider-user2
111--->172.20.10.4:7900:microservice-provider-user
222--->172.20.10.4:7800:microservice-provider-user2
111--->172.20.10.4:7900:microservice-provider-user
222--->172.20.10.4:7801:microservice-provider-user2
111--->172.20.10.4:7900:microservice-provider-user
222--->172.20.10.4:7800:microservice-provider-user2
111--->172.20.10.4:7900:microservice-provider-user
222--->172.20.10.4:7801:microservice-provider-user2
111--->172.20.10.4:7901:microservice-provider-user
222--->172.20.10.4:7800:microservice-provider-user2
111--->172.20.10.4:7900:microservice-provider-user
222--->172.20.10.4:7801:microservice-provider-user2
111--->172.20.10.4:7900:microservice-provider-user
222--->172.20.10.4:7800:microservice-provider-user2
111--->172.20.10.4:7900:microservice-provider-user
222--->172.20.10.4:7801:microservice-provider-user2
111--->172.20.10.4:7900:microservice-provider-user
222--->172.20.10.4:7800:microservice-provider-user2
111--->172.20.10.4:7901:microservice-provider-user
222--->172.20.10.4:7801:microservice-provider-user2
111--->172.20.10.4:7900:microservice-provider-user
222--->172.20.10.4:7800:microservice-provider-user2
111--->172.20.10.4:7900:microservice-provider-user
222--->172.20.10.4:7801:microservice-provider-user2
111--->172.20.10.4:7900:microservice-provider-user
222--->172.20.10.4:7800:microservice-provider-user2
111--->172.20.10.4:7901:microservice-provider-user
222--->172.20.10.4:7801:microservice-provider-user2
111--->172.20.10.4:7901:microservice-provider-user
222--->172.20.10.4:7800:microservice-provider-user2

 

5.4. 使用屬性自定義Ribbon配置

pom.xml算法

<?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">
    <modelVersion>4.0.0</modelVersion>

    <artifactId>microservice-consumer-movie-ribbon-config</artifactId>
    <packaging>jar</packaging>

    <parent>
        <groupId>com.itmuch.cloud</groupId>
        <artifactId>microservice-spring-cloud</artifactId>
        <version>0.0.1-SNAPSHOT</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>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</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-actuator</artifactId>
        </dependency>
    </dependencies>
</project>

配置文件spring

spring:
  application:
    name: microservice-consumer-movie-ribbon-config
server:
  port: 8010
eureka:
  client:
    healthcheck:
      enabled: true
    serviceUrl:
      defaultZone: http://user:password123@localhost:8761/eureka
  instance:
    prefer-ip-address: true
microservice-provider-user:
  ribbon:
    NFLoadBalancerRuleClassName: com.netflix.loadbalancer.WeightedResponseTimeRule
     

實體類apache

package com.itmuch.cloud.entity;

import java.math.BigDecimal;

public class User {
  private Long id;

  private String username;

  private String name;

  private Short age;

  private BigDecimal balance;

  public Long getId() {
    return this.id;
  }

  public void setId(Long id) {
    this.id = id;
  }

  public String getUsername() {
    return this.username;
  }

  public void setUsername(String username) {
    this.username = username;
  }

  public String getName() {
    return this.name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public Short getAge() {
    return this.age;
  }

  public void setAge(Short age) {
    this.age = age;
  }

  public BigDecimal getBalance() {
    return this.balance;
  }

  public void setBalance(BigDecimal balance) {
    this.balance = balance;
  }

}

Controller類服務器

package com.itmuch.cloud.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.itmuch.cloud.entity.User;

@RestController
public class MovieController {
  @Autowired
  private RestTemplate restTemplate;
  @Autowired
  private LoadBalancerClient  loadBalancerClient;
 
  @GetMapping("/movie/{id}")
  public User findById(@PathVariable Long id) {
     
    return this.restTemplate.getForObject("http://microservice-provider-user/simple/" + id, User.class);
  }
    @GetMapping("/test")
    public String test(){
    ServiceInstance     serviceInstance=this.loadBalancerClient.choose("microservice-provider-user");
    System.out.println("cyj:--->"+serviceInstance.getHost()+":"+serviceInstance.getPort()+":"+serviceInstance.getServiceId());
    
    ServiceInstance     serviceInstance2=this.loadBalancerClient.choose("microservice-provider-user2");
    System.out.println("lxq:--->"+serviceInstance2.getHost()+":"+serviceInstance2.getPort()+":"+serviceInstance2.getServiceId());
   
    return "1";
    }
}

圖文app

 

5.5. 脫離Eureka使用Ribbon

Eureka是一種方便的方式來抽象遠程服務器的發現,所以您沒必要在客戶端中對其URL進行硬編碼,

但若是您不想使用它,Ribbon和Feign仍然是適用的。假設您已經爲「商店」申請了@RibbonClient

而且Eureka未被使用(甚至不在類路徑上)。Ribbon客戶端默認爲已配置的服務器列表,

您能夠提供這樣的配置

stores:
  ribbon:
    listOfServers: example.com,google.com

在Ribbon中禁用Eureka使用

ribbon:
  eureka:
   enabled: false

設置屬性ribbon.eureka.enabled = false將明確禁用在Ribbon中使用Eureka。

 
spring:
  application:
    name: microservice-consumer-movie-ribbon-config
server:
  port: 8010
eureka:
  client:
    healthcheck:
      enabled: true
    serviceUrl:
      defaultZone: http://user:password123@localhost:8761/eureka
  instance:
    prefer-ip-address: true
ribbon:
  eureka:
   enabled: false      
microservice-provider-user:
   ribbon:
     listOfServers: localhost:7800
 
相關文章
相關標籤/搜索