Introduction to Spring Cloud Rest Client with Netflix Ribbon – 使用Netflix Ribbon的Spring Cloud Rest Client介绍

最后修改: 2016年 11月 10日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.介绍

Netflix Ribbon is an Inter Process Communication (IPC) cloud library. Ribbon primarily provides client-side load balancing algorithms.

Netflix Ribbon是一个进程间通信(IPC)云库。Ribbon主要提供客户端的负载平衡算法。

Apart from the client-side load balancing algorithms, Ribbon provides also other features:

除了客户端的负载平衡算法外,Ribbon还提供了其他功能。

  • Service Discovery Integration – Ribbon load balancers provide service discovery in dynamic environments like a cloud. Integration with Eureka and Netflix service discovery component is included in the ribbon library
  • Fault Tolerance – the Ribbon API can dynamically determine whether the servers are up and running in a live environment and can detect those servers that are down
  • Configurable load-balancing rules – Ribbon supports RoundRobinRule, AvailabilityFilteringRule, WeightedResponseTimeRule out of the box and also supports defining custom rules

Ribbon API works based on the concept called “Named Client”. While configuring Ribbon in our application configuration file we provide a name for the list of servers included for the load balancing.

Ribbon API的工作原理是基于 “命名客户 “的概念。在我们的应用程序配置文件中配置Ribbon时,我们提供了一个用于负载平衡的服务器列表的名称。

Let’s take it for a spin.

让我们去转一转。

2. Dependency Management

2.依赖性管理

The Netflix Ribbon API can be added to our project by adding the below dependency to our pom.xml:

通过在我们的pom.xml中添加以下依赖关系,Netflix Ribbon API可以被添加到我们的项目中:

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

The latest libraries can be found here.

最新的库可以在这里找到。

3. Example Application

3.应用实例

In order to see the working of Ribbon API, we build a sample microservice application with Spring RestTemplate and we enhance it with Netflix Ribbon API along with Spring Cloud Netflix API.

为了了解Ribbon API的工作情况,我们用Spring RestTemplate构建了一个样本微服务应用程序,并利用Netflix Ribbon API和Spring Cloud Netflix API对其进行了强化。

We’ll use one of Ribbon’s load-balancing strategies, WeightedResponseTimeRule, to enable the client side load balancing between 2 servers, which are defined under a named client in the configuration file, in our application.

我们将使用Ribbon的负载平衡策略之一,WeightedResponseTimeRule,来实现客户端的负载平衡,在我们的应用程序中,2个服务器被定义在一个名为客户的配置文件下。

4. Ribbon Configuration

4.色带配置

Ribbon API enables us to configure the following components of the load balancer:

Ribbon API使我们能够配置负载平衡器的以下组件。

  • Rule – Logic component which specifies the load balancing rule we are using in our application
  • Ping – A Component which specifies the mechanism we use to determine the server’s availability in real-time
  • ServerList – can be dynamic or static. In our case, we are using a static list of servers and hence we are defining them in the application configuration file directly

Let write a simple configuration for the library:

让我们为这个库写一个简单的配置。

public class RibbonConfiguration {

    @Autowired
    IClientConfig ribbonClientConfig;

    @Bean
    public IPing ribbonPing(IClientConfig config) {
        return new PingUrl();
    }

    @Bean
    public IRule ribbonRule(IClientConfig config) {
        return new WeightedResponseTimeRule();
    }
}

Notice how we used the WeightedResponseTimeRule rule to determine the server and PingUrl mechanism to determine the server’s availability in real-time.

注意我们是如何使用WeightedResponseTimeRule规则来确定服务器和PingUrl机制来实时确定服务器的可用性。

According to this rule, each server is given a weight according to its average response time, lesser the response time gives lesser the weight. This rule randomly selects a server where the possibility is determined by server’s weight.

根据这一规则,每个服务器根据其平均响应时间被赋予一个权重,响应时间越少,权重越小。这个规则随机选择一个服务器,其可能性由服务器的权重决定。

And the PingUrl will ping every URL to determine the server’s availability.

PingUrl将对每个URL进行ping,以确定服务器的可用性。

5. application.yml

5.application.yml

Below is the application.yml configuration file we created for this sample application:

下面是我们为这个示例应用程序创建的application.yml配置文件。

spring:
  application:
    name: spring-cloud-ribbon

server:
  port: 8888

ping-server:
  ribbon:
    eureka:
      enabled: false
    listOfServers: localhost:9092,localhost:9999
    ServerListRefreshInterval: 15000

In the above file, we specified:

在上述文件中,我们指定。

  • Application name
  • Port number of the application
  • Named client for the list of servers: “ping-server”
  • Disabled Eureka service discovery component, by setting eureka: enabled to false
  • Defined the list of servers available for load balancing, in this case, 2 servers
  • Configured the server refresh rate with ServerListRefreshInterval

6. RibbonClient

6.RibbonClient

Let’s now set up the main application component snippet – where we use the RibbonClient to enable the load balancing instead of the plain RestTemplate:

现在让我们来设置主要的应用程序组件片段–在这里我们使用RibbonClient来启用负载均衡,而不是使用普通的RestTemplate

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

    @Autowired
    RestTemplate restTemplate;

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

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

And here’s the RestTemplate configuration:

这里是RestTemplate配置。

@Configuration
public class RestTemplateConfiguration{
    @LoadBalanced
    @Bean
    RestTemplate getRestTemplate() {
        return new RestTemplate();
    }
}

We defined a controller class with the annotation @RestController; we also annotated the class with @RibbonClient with a name and a configuration class.

我们用注解@RestController定义了一个控制器类;我们还用@RibbonClient注解了这个类的名称和一个配置类。

The configuration class we defined here is the same class that we defined before in which we provided the desired Ribbon API configuration for this application.

我们在这里定义的配置类与之前定义的类相同,在该类中我们为这个应用程序提供了所需的Ribbon API配置。

Notice we annotated the RestTemplate with @LoadBalanced which suggests that we want this to be load balanced and in this case with Ribbon.

请注意,我们在RestTemplate上注释了@LoadBalanced,这表明我们希望它是负载平衡的,而且在这种情况下是与Ribbon一起。

7. Failure Resiliency in Ribbon

7.丝带的故障恢复能力

As we discussed earlier in this article, Ribbon API not only provides client side load balancing algorithms but also it has built in failure resiliency.

正如我们在本文前面所讨论的,Ribbon API不仅提供了客户端的负载平衡算法,而且它还内置了故障恢复能力。

As stated before, Ribbon API can determine the server’s availability through the constant pinging of servers at regular intervals and has a capability of skipping the servers which are not live.

如前所述,Ribbon API可以通过定期对服务器进行不断的ping来确定服务器的可用性,并有能力跳过不在线的服务器。

In addition to that, it also implements Circuit Breaker pattern to filter out the servers based on specified criteria.

除此之外,它还实现了Circuit Breaker模式,根据指定标准过滤掉服务器。

The Circuit Breaker pattern minimizes the impact of a server failure on performance by swiftly rejecting a request to that server that is failing without waiting for a time-out. We can disable this Circuit Breaker feature by setting the property niws.loadbalancer.availabilityFilteringRule.filterCircuitTripped to false.

Circuit Breaker 模式通过迅速拒绝对该故障服务器的请求而不等待超时,将服务器故障对性能的影响降到最低。我们可以通过将属性niws.loadbalancer.availabilityFilteringRule.filterCircuitTripped设为false来禁用这个Circuit Breaker功能。

When all servers are down, thus no server is available to serve the request, the pingUrl() will fail and we receive an exception java.lang.IllegalStateException with a message “No instances are available to serve the request”.

当所有的服务器都关闭时,因此没有服务器可以为请求提供服务,pingUrl()将失败,我们会收到一个异常java.lang.IllegalStateException,信息“没有实例可以为请求提供服务”

8. Conclusion

8.结论

In this article, we discussed Netflix Ribbon API and its implementation in a simple sample application.

在这篇文章中,我们讨论了Netflix Ribbon API以及它在一个简单的示例应用程序中的实现。

The complete source code for the example described above can be found on the GitHub repository.

上述例子的完整源代码可以在GitHub资源库中找到。