Spring-Cloud-Netflix官方文档翻译2.2.4

Spring-Cloud-Netflix 2.2.4.RELEASE


This project provides Netflix OSS integrations for Spring Boot apps through autoconfiguration and binding to the Spring Environment and other Spring programming model idioms. With a few simple annotations you can quickly enable and configure the common patterns inside your application and build large distributed systems with battle-tested Netflix components. The patterns provided include Service Discovery (Eureka), Circuit Breaker (Hystrix), Intelligent Routing (Zuul) and Client Side Load Balancing (Ribbon).
这个项目通过绑定Spring环境和其他Spring模型语言为Spring Boot 应用提供 Netflix OSS集成。通过一些简单的注解,你可以在你的应用里快速启动、配置一些通用模式,并通过经过实际检验的Netflix组件来构建一个大型分布式系统。提供的模式包括服务发现 (Eureka), 断路器 (Hystrix),智能路由(Zuul) 和客户端方面的负载均衡(Ribbon)。

1.服务发现:Eureka 客户端

Service Discovery is one of the key tenets of a microservice-based architecture. Trying to hand-configure each client or some form of convention can be difficult to do and can be brittle. Eureka is the Netflix Service Discovery Server and Client. The server can be configured and deployed to be highly available, with each server replicating state about the registered services to the others.
服务发现是基于微服务架构的关键原则之一。手动配置每个客户端或某些准则会既复杂又脆弱。Eureka是Netflix服务发现的服务器和客户端。服务器可以被配置和部署为高可用,每个服务器都把注册服务的状态复制给其他服务器。

1.1.如何引入Eureka客户端

To include the Eureka Client in your project, use the starter with a group ID of org.springframework.cloud and an artifact ID of spring-cloud-starter-netflix-eureka-client. See the Spring Cloud Project page for details on setting up your build system with the current Spring Cloud Release Train.

	<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-netflix-eureka-client -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    <version>2.2.4.RELEASE</version>
</dependency>

1.2.用Eureka注册

When a client registers with Eureka, it provides meta-data about itself — such as host, port, health indicator URL, home page, and other details. Eureka receives heartbeat messages from each instance belonging to a service. If the heartbeat fails over a configurable timetable, the instance is normally removed from the registry.

当客户端在Eureka注册时,它会提供关于自身的元数据——比如主机名、端口号、健康显示器URL、主页和其他详细资料。Eureka从每个服务实例处接收心跳信息。如果心跳超过配置的时间表,该实例通常会从注册表中删除。
The following example shows a minimal Eureka client application:
下面的例子展示了最简Eureka客户端应用。

@SpringBootApplication
@RestController
public class Application {

    @RequestMapping("/")
    public String home() {
        return "Hello world";
    }

    public static void main(String[] args) {
        new SpringApplicationBuilder(Application.class).web(true).run(args);
    }

}

Note that the preceding example shows a normal Spring Boot application. By having spring-cloud-starter-netflix-eureka-client on the classpath, your application automatically registers with the Eureka Server. Configuration is required to locate the Eureka server, as shown in the following example:

注意,前面的示例展示了一个普通的Spring Boot应用。通过在类路径中设置spring-cloud- starter -netflix- Eureka -client,您的应用将自动注册到Eureka服务器。定位到Eureka服务器需要配置,如下面的示例所示:

application.yml

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/

In the preceding example, defaultZone is a magic string fallback value that provides the service URL for any client that does not express a preference (in other words, it is a useful default).

在上述的示例中,defaultZone是一个神奇的字符串回调值,它为任何不表示首选项的客户机提供服务URL(换句话说,它是一个有用的默认值)。

The defaultZone property is case sensitive and requires camel case because the serviceUrl property is a Map<String, String>. Therefore, the defaultZone property does not follow the normal Spring Boot snake-case convention of default-zone.

defaultZone属性大小写敏感,并且需要驼峰大小写,因为serviceUrl属性是一个Map<String, String>。因此,defaultZone属性并不遵循普通的Spring Boot蛇形命名法约定。

The default application name (that is, the service ID), virtual host, and non-secure port (taken from the Environment) are ${spring.application.name}, ${spring.application.name} and ${server.port}, respectively.

默认的应用程序名称(即服务ID)、虚拟主机和不安全端口(取自Environment)分别是是${spring.application.name}${spring.application.name}${server.port}

Having spring-cloud-starter-netflix-eureka-client on the classpath makes the app into both a Eureka “instance” (that is, it registers itself) and a “client” (it can query the registry to locate other services). The instance behaviour is driven by eureka.instance.* configuration keys, but the defaults are fine if you ensure that your application has a value for spring.application.name (this is the default for the Eureka service ID or VIP).

在类路径中设置spring-cloud- starker -netflix- Eureka -client可以使应用程序成为Eureka“实例”(也就是说,它注册自己)和“客户端”(它可以查询注册表来定位其他服务)。实例行为由eureka.instance.*配置项驱动,但是如果你的应用程序有spring.application.name的值(这是Eureka服务ID或VIP的默认值),使用默认值即可。

See EurekaInstanceConfigBean and EurekaClientConfigBean for more details on the configurable options.

To disable the Eureka Discovery Client, you can set eureka.client.enabled to false. Eureka Discovery Client will also be disabled when spring.cloud.discovery.enabled is set to false.

若要禁用Eureka发现客户端,可以设置eureka.client.enabledfalse。当spring.cloud.discovery.enabled设置为false时,Eureka发现客户端也将被禁用。

1.3.使用Eureka进行身份验证

HTTP basic authentication is automatically added to your eureka client if one of the eureka.client.serviceUrl.defaultZone URLs has credentials embedded in it (curl style, as follows: user:password@localhost:8761/eureka). For more complex needs, you can create a @Bean of type DiscoveryClientOptionalArgs and inject ClientFilter instances into it, all of which is applied to the calls from the client to the server.

如果一个eureka.client.serviceUrl.defaultZoneURL嵌入了证书(风格如下:user:password@localhost:8761/eureka),HTTP基础认证就会被自动添加进你的Eureka客户端。对于更复杂的需求,您可以创建类型为DiscoveryClientOptionalArgs@Bean,并将ClientFilter`实例注入其中,所有这些都应用于客户机对服务器的调用。
Because of a limitation in Eureka, it is not possible to support per-server basic auth credentials, so only the first set that are found is used.
由于Eureka中的限制,不可能支持每台服务器的基本身份验证凭证,因此只有找到的第一组使用了身份验证。

1.4.状态页面和健康指示器

The status page and health indicators for a Eureka instance default to /info and /health respectively, which are the default locations of useful endpoints in a Spring Boot Actuator application. You need to change these, even for an Actuator application if you use a non-default context path or servlet path (such as server.servletPath=/custom). The following example shows the default values for the two settings:

Eureka实例的状态页和健康指示器分别默认为/info/health,这是Spring Boot Actuator应用中实用端点的默认位置。如果使用非默认上下文路径或servlet路径(如server.servletPath=/custom),那么即使对于执行器应用,也需要更改这些内容。下面的示例显示了这两种设置的默认值:
application.yml

eureka:
  instance:
    statusPageUrlPath: ${server.servletPath}/info
    healthCheckUrlPath: ${server.servletPath}/health

These links show up in the metadata that is consumed by clients and are used in some scenarios to decide whether to send requests to your application, so it is helpful if they are accurate.

这些链接显示在客户端使用的元数据中,并在某些场景中用于决定是否向应用程序发送请求,因此如果它们是准确的,将很有帮助。

In Dalston it was also required to set the status and health check URLs when changing that management context path. This requirement was removed beginning in Edgware.

在Dalston中,还需要在更改管理上下文路径时设置状态和运行状况检查url。这个要求从Edgware开始就被删除了。

1.5.注册安全应用程序

If your app wants to be contacted over HTTPS, you can set two flags in the EurekaInstanceConfig:

如果你的APP想要通过HTTPS被联系,你可以在EurekaInstanceConfig设置两个标识:

eureka.instance.[nonSecurePortEnabled]=[false]

eureka.instance.[securePortEnabled]=[true]

Doing so makes Eureka publish instance information that shows an explicit preference for secure communication. The Spring Cloud DiscoveryClient always returns a URI starting with https for a service configured this way. Similarly, when a service is configured this way, the Eureka (native) instance information has a secure health check URL.

这样做可以使Eureka发布显示对安全通信的显式偏好的实例信息。以这种方式配置的服务,Spring Cloud DiscoveryClient总是返回一个以https开头的URI。类似地,当以这种方式配置服务时,Eureka(本机)实例信息有一个安全健康状况检查URL。

Because of the way Eureka works internally, it still publishes a non-secure URL for the status and home pages unless you also override those explicitly. You can use placeholders to configure the eureka instance URLs, as shown in the following example:

由于Eureka内部工作的方式,它仍然为状态页和主页发布一个不安全的URL,除非您也显式地覆盖它们。您可以使用占位符来配置eureka实例的url,如下面的例子所示:
application.yml

eureka:
  instance:
    statusPageUrl: https://${eureka.hostname}/info
    healthCheckUrl: https://${eureka.hostname}/health
    homePageUrl: https://${eureka.hostname}/

(Note that ${eureka.hostname} is a native placeholder only available in later versions of Eureka. You could achieve the same thing with Spring placeholders as well — for example, by using ${eureka.instance.hostName}.)

(注意,${eureka.hostname}是一个本地占位符,仅在Eureka的后续版本中可用。您也可以使用Spring占位符来实现同样的功能—例如,通过使用' ${eureka.instance.hostName} '。)

If your application runs behind a proxy, and the SSL termination is in the proxy (for example, if you run in Cloud Foundry or other platforms as a service), then you need to ensure that the proxy “forwarded” headers are intercepted and handled by the application. If the Tomcat container embedded in a Spring Boot application has explicit configuration for the 'X-Forwarded-*` headers, this happens automatically. The links rendered by your app to itself being wrong (the wrong host, port, or protocol) is a sign that you got this configuration wrong.

如果您的应用运行在代理之后,而SSL终端在代理中(例如,如果您作为一个服务运行在Cloud Foundry或其他平台),那么您需要确保代理“forwarded” headers被应用拦截和处理。如果在Spring Boot应用中嵌入的Tomcat容器对“X-Forwarded-”headers,有显式配置,那么这将自动发生。如果你的应用程序所呈现的链接本身是错误的(错误的主机、端口或协议),这是一个信号,表明你的配置是错误的。*

1.6.Eureka的健康检查

By default, Eureka uses the client heartbeat to determine if a client is up. Unless specified otherwise, the Discovery Client does not propagate the current health check status of the application, per the Spring Boot Actuator. Consequently, after successful registration, Eureka always announces that the application is in ‘UP’ state. This behavior can be altered by enabling Eureka health checks, which results in propagating application status to Eureka. As a consequence, every other application does not send traffic to applications in states other then ‘UP’. The following example shows how to enable health checks for the client:

默认情况下,Eureka使用客户端心跳来确定客户端是否已启动。除非另有指定,否则Discovery Client不会为每个Spring Boot Actuator的传播应用当前健康检查状态。因此,在成功注册后,Eureka总是宣布应用程序处于“UP”状态。可以通过启用Eureka健康状况检查来更改此行为,这将导致将应用程序状态传播到Eureka。因此,其他所有应用都不会向处于不处于“UP”状态的应用发送通信。下面的示例显示如何为客户机启用运行状况检查:
application.yml

eureka:
  client:
    healthcheck:
      enabled: true

eureka.client.healthcheck.enabled=true should only be set in application.yml. Setting the value in bootstrap.yml causes undesirable side effects, such as registering in Eureka with an UNKNOWN status.

eureka.client.healthcheck.enabled=true只能在application.yml中设置。在bootstrap.yml中设置值会引起不良的副作用,例如在Eureka注册时状态未知。

If you require more control over the health checks, consider implementing your own com.netflix.appinfo.HealthCheckHandler.

如果你需要对运行状况检查有更多的控制,可以考虑自己实现com.netflix.appinfo.HealthCheckHandler

1.7.实例和客户端的Eureka元数据

It is worth spending a bit of time understanding how the Eureka metadata works, so you can use it in a way that makes sense in your platform. There is standard metadata for information such as hostname, IP address, port numbers, the status page, and health check. These are published in the service registry and used by clients to contact the services in a straightforward way. Additional metadata can be added to the instance registration in the eureka.instance.metadataMap, and this metadata is accessible in the remote clients. In general, additional metadata does not change the behavior of the client, unless the client is made aware of the meaning of the metadata. There are a couple of special cases, described later in this document, where Spring Cloud already assigns meaning to the metadata map.

很有必要花点时间了解Eureka元数据是如何工作,这样您就可以在您的平台中以一种有意义的方式使用它。对于诸如主机名、IP地址、端口号、状态页和运行状况检查等信息,有标准的元数据。这些元数据在服务注册中心中发布,客户机使用它们以一种直接的方式联系服务。可以在eureka.instance.metadataMap中将其他的元数据添加到实例注册表中,该元数据可以在远程客户端访问。一般来说,附加的元数据不会改变客户端的行为,除非客户机知道元数据的意义。有一些特殊的情况,在本文档后面会描述,其中Spring Cloud已经为元数据map分配了含义。

1.7.1.在Cloud Foundry上使用Eureka

Cloud Foundry has a global router so that all instances of the same app have the same hostname (other PaaS solutions with a similar architecture have the same arrangement). This is not necessarily a barrier to using Eureka. However, if you use the router (recommended or even mandatory, depending on the way your platform was set up), you need to explicitly set the hostname and port numbers (secure or non-secure) so that they use the router. You might also want to use instance metadata so that you can distinguish between the instances on the client (for example, in a custom load balancer). By default, the eureka.instance.instanceId is vcap.application.instance_id, as shown in the following example:

Cloud Foundry有一个全局路由器,因此同一个应用的所有实例都有相同的主机名(其他具有类似架构的平台服务解决方案也有相同的安排)。这并不一定是使用Eureka的障碍。但是,如果您使用路由器(推荐的,甚至是强制的,这取决于平台的设置方式),您需要显式地设置主机名和端口号(安全的或不安全的),以便它们使用路由器。您可能还希望使用实例元数据,以便能够区分客户机上的实例(例如,在自定义负载均衡器中)。默认情况下,eureka.instance.instanceId 就是vcap.application.instance_id,如下面的示例所示:
application.yml

eureka:
  instance:
    hostname: ${vcap.application.uris[0]}
    nonSecurePort: 80

Depending on the way the security rules are set up in your Cloud Foundry instance, you might be able to register and use the IP address of the host VM for direct service-to-service calls. This feature is not yet available on Pivotal Web Services (PWS).

根据在您的Cloud Foundry实例中设置安全规则的方式,您可能能够注册和使用主机VM的IP地址来进行直接的service-to-service调用。这个特性还不能在Pivotal Web Services (PWS)上使用。

1.7.2.在AWS上使用Eureka

If the application is planned to be deployed to an AWS cloud, the Eureka instance must be configured to be AWS-aware. You can do so by customizing the EurekaInstanceConfigBean as follows:

如果计划将应用程序部署到AWS云,那么Eureka实例必须配置为支持AWS的。你可以自定义EurekaInstanceConfigBean如下:

@Bean
@Profile("!default")
public EurekaInstanceConfigBean eurekaInstanceConfig(InetUtils inetUtils) {
  EurekaInstanceConfigBean b = new EurekaInstanceConfigBean(inetUtils);
  AmazonInfo info = AmazonInfo.Builder.newBuilder().autoBuild("eureka");
  b.setDataCenterInfo(info);
  return b;
}

1.7.3.改变Eureka实例ID

A vanilla Netflix Eureka instance is registered with an ID that is equal to its host name (that is, there is only one service per host). Spring Cloud Eureka provides a sensible default, which is defined as follows:

一个普通的Netflix Eureka实例使用一个ID注册,这个ID等于它的主机名(也就是说,每个主机只有一个服务)。Spring Cloud Eureka提供了一个合理的默认值,其定义如下:

${spring.cloud.client.hostname}:${spring.application.name}:${spring.application.instance_id:${server.port}}}

An example is myhost:myappname:8080.

例如myhost:myappname:8080.

By using Spring Cloud, you can override this value by providing a unique identifier in eureka.instance.instanceId, as shown in the following example:

使用Spring Cloud,您可以通过在eureka.instance.instanceId中提供一个唯一标识符来覆盖这个值。如下例所示:
application.yml

eureka:
  instance:
    instanceId: ${spring.application.name}:${vcap.application.instance_id:${spring.application.instance_id:${random.value}}}

With the metadata shown in the preceding example and multiple service instances deployed on localhost, the random value is inserted there to make the instance unique. In Cloud Foundry, the vcap.application.instance_id is populated automatically in a Spring Boot application, so the random value is not needed.

对于前面示例中显示的元数据和部署在本地主机上的多个服务实例,将在其中插入随机值以使该实例唯一。在Cloud Foundry中,vcap.application.instance_id将自动填充到Spring Boot应用程序中,因此不需要随机值。

1.8.使用Eureka客户端

Once you have an application that is a discovery client, you can use it to discover service instances from the Eureka Server. One way to do so is to use the native com.netflix.discovery.EurekaClient (as opposed to the Spring Cloud DiscoveryClient), as shown in the following example:

一旦有了作为发现客户端的应用程序,就可以使用它从Eureka服务器发现服务实例。一种方法是使用本地com.netflix.discovery.EurekaClient(相对于Spring Cloud DiscoveryClient),如下例所示:

@Autowired
private EurekaClient discoveryClient;

public String serviceUrl() {
    InstanceInfo instance = discoveryClient.getNextServerFromEureka("STORES", false);
    return instance.getHomePageUrl();
}

Do not use the EurekaClient in a @PostConstruct method or in a @Scheduled method (or anywhere where the ApplicationContext might not be started yet). It is initialized in a SmartLifecycle (with phase=0), so the earliest you can rely on it being available is in another SmartLifecycle with a higher phase.

不要在@PostConstruct方法或@Scheduled方法(或任何ApplicationContext还没有启动的地方)中使用EurekaClient。它在一个SmartLifecycle (phase=0)中初始化,所以您可以依赖它可用的最早时间是在另一个更高阶段的SmartLifecycle中。

1.8.1.不使用Jersey的Eureka客户端

By default, EurekaClient uses Jersey for HTTP communication. If you wish to avoid dependencies from Jersey, you can exclude it from your dependencies. Spring Cloud auto-configures a transport client based on Spring RestTemplate. The following example shows Jersey being excluded:

默认情况下,EurekaClient使用Jersey进行HTTP通信。如果希望避免来自Jersey的依赖项,可以将其从依赖项中排除。Spring Cloud基于Spring RestTemplate自动配置传输客户端。下面的例子显示了Jers

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    <exclusions>
        <exclusion>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-client</artifactId>
        </exclusion>
        <exclusion>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-core</artifactId>
        </exclusion>
        <exclusion>
            <groupId>com.sun.jersey.contribs</groupId>
            <artifactId>jersey-apache-client4</artifactId>
        </exclusion>
    </exclusions>
</dependency>

1.9.Native Netflix Eureka的替代品

You need not use the raw Netflix EurekaClient. Also, it is usually more convenient to use it behind a wrapper of some sort. Spring Cloud has support for Feign (a REST client builder) and Spring RestTemplate through the logical Eureka service identifiers (VIPs) instead of physical URLs. To configure Ribbon with a fixed list of physical servers, you can set <client>.ribbon.listOfServers to a comma-separated list of physical addresses (or hostnames), where <client> is the ID of the client.

你不需要使用原始的Netflix EurekaClient 。而且,在某种包装器后面使用它通常更方便。Spring Cloud通过逻辑Eureka服务标识符(vip)而不是物理url支持Feign(一个REST客户端构建器)和Spring RestTemplate 。要使用固定的物理服务器列表配置Ribbon,可以设置 <client>.ribbon.listOfServers ,以逗号分隔的物理地址(或主机名)列表,其中<client>是客户机的ID。

You can also use the org.springframework.cloud.client.discovery.DiscoveryClient, which provides a simple API (not specific to Netflix) for discovery clients, as shown in the following example:

您还可以使用org.springframework.cloud.client.discovery。它为发现客户端提供了一个简单的API(不是特定于Netflix的),如下面的示例所示:

@Autowired
private DiscoveryClient discoveryClient;

public String serviceUrl() {
    List<ServiceInstance> list = discoveryClient.getInstances("STORES");
    if (list != null && list.size() > 0 ) {
        return list.get(0).getUri();
    }
    return null;
}

1.10.为什么注册服务这么慢

Being an instance also involves a periodic heartbeat to the registry (through the client’s serviceUrl) with a default duration of 30 seconds. A service is not available for discovery by clients until the instance, the server, and the client all have the same metadata in their local cache (so it could take 3 heartbeats). You can change the period by setting eureka.instance.leaseRenewalIntervalInSeconds. Setting it to a value of less than 30 speeds up the process of getting clients connected to other services. In production, it is probably better to stick with the default, because of internal computations in the server that make assumptions about the lease renewal period.

作为一个实例,还包括到注册中心的周期心跳(通过客户机的serviceUrl),默认持续时间为30秒。在实例、服务器和客户端在其本地缓存中都具有相同的元数据之前,客户端无法发现服务(因此可能需要3次心跳)。您可以通过设置eureka.instance.leaseRenewalIntervalInSeconds来更改周期。将其设置为小于30的值可以加速客户机连接到其他服务的过程。在生产环境中,坚持使用缺省值可能更好,因为服务器中的内部计算会对租约续订期进行假设。

1.11. Zones

If you have deployed Eureka clients to multiple zones, you may prefer that those clients use services within the same zone before trying services in another zone. To set that up, you need to configure your Eureka clients correctly.

如果您已经将Eureka客户端部署到多个区域,您可能希望这些客户端在尝试另一个区域的服务之前先使用同一个区域内的服务。要进行设置,您需要正确配置Eureka客户机。
First, you need to make sure you have Eureka servers deployed to each zone and that they are peers of each other. See the section on zones and regions for more information.

首先,您需要确保每个区域都部署了Eureka服务器,并且它们彼此是对等的。有关更多信息,请参阅区域和区域一节。

Next, you need to tell Eureka which zone your service is in. You can do so by using the metadataMap property. For example, if service 1 is deployed to both zone 1 and zone 2, you need to set the following Eureka properties in service 1:

接下来,你需要告诉Eureka你的服务在哪个区域。可以通过使用metadataMap属性来实现这一点。例如,如果服务1同时部署到区域1和区域2,您需要在服务1中设置以下Eureka属性:

Service 1 in Zone 1

eureka.instance.metadataMap.zone = zone1
eureka.client.preferSameZoneEureka = true

Service 1 in Zone 2

eureka.instance.metadataMap.zone = zone2
eureka.client.preferSameZoneEureka = true

1.12.刷新Eureka客户端

By default, the EurekaClient bean is refreshable, meaning the Eureka client properties can be changed and refreshed. When a refresh occurs clients will be unregistered from the Eureka server and there might be a brief moment of time where all instance of a given service are not available. One way to eliminate this from happening is to disable the ability to refresh Eureka clients. To do this set eureka.client.refresh.enable=false.

默认情况下,EurekaClient bean是可刷新的,这意味着Eureka客户端属性可以更改和刷新。刷新时,客户端将取消在Eureka服务端上的注册,提供服务的所有实例可能会有一段短暂的时间不可用。消除这种情况的一种方法是禁用刷新Eureka客户端的功能。为此设置eureka.client.refresh.enable=false

1.13.和Spring Cloud负载均衡器一起使用Eureka

We offer support for the Spring Cloud LoadBalancer ZonePreferenceServiceInstanceListSupplier. The zone value from the Eureka instance metadata (eureka.instance.metadataMap.zone) is used for setting the value of spring-clod-loadbalancer-zone property that is used to filter service instances by zone.

我们提供对Spring Cloud LoadBalancer ZonePreferenceServiceInstanceListSupplier的支持。来自Eureka实例元数据(Eureka .instance. metadatamap.zone)的zone值用于设置spring-clod-loadbalance -zone属性的值,该属性用于按区域筛选服务实例。

If that is missing and if the spring.cloud.loadbalancer.eureka.approximateZoneFromHostname flag is set to true, it can use the domain name from the server hostname as a proxy for the zone.

如果那个丢失了且spring.cloud.loadbalancer.eureka.approximateZoneFromHostname标志设置为true,它可以使用来自服务器主机名的域名作为区域的代理。

If there is no other source of zone data, then a guess is made, based on the client configuration (as opposed to the instance configuration). We take eureka.client.availabilityZones, which is a map from region name to a list of zones, and pull out the first zone for the instance’s own region (that is, the eureka.client.region, which defaults to “us-east-1”, for compatibility with native Netflix).

如果没有其他来源的区域数据,则根据客户端配置(而不是实例配置)进行猜测。我们取eureka.client.availabilityZones,它是一个从地区名称到区域列表的映射,并为实例自己的地区提取第一个区域(即eureka.client.region,默认为“us-east-1”,以与本地Netflix兼容)。

2.服务发现Eureka Server

This section describes how to set up a Eureka server.
本节描述如何设置Eureka服务器。

2.1.引入Eureka Server

To include Eureka Server in your project, use the starter with a group ID of org.springframework.cloud and an artifact ID of spring-cloud-starter-netflix-eureka-server. See the Spring Cloud Project page for details on setting up your build system with the current Spring Cloud Release Train.

<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-netflix-eureka-server -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
    <version>2.2.4.RELEASE</version>
</dependency>

If your project already uses Thymeleaf as its template engine, the Freemarker templates of the Eureka server may not be loaded correctly. In this case it is necessary to configure the template loader manually:
如果你的工程中已经使用了Thymeleaf作为模板引擎,Freemarker模板引擎可能不会正确加载。因此非常必要手动配置模板加载。

application.yml

spring:
  freemarker:
    template-loader-path: classpath:/templates/
    prefer-file-system-access: false

2.2.如何启动Eureka Server

The following example shows a minimal Eureka server:

@SpringBootApplication
@EnableEurekaServer
public class Application {

    public static void main(String[] args) {
        new SpringApplicationBuilder(Application.class).web(true).run(args);
    }

}

The server has a home page with a UI and HTTP API endpoints for the normal Eureka functionality under /eureka/*.

服务器在’ / Eureka /* '下有一个带有UI和HTTP API端点的主页,用于正常Eureka功能。

The following links have some Eureka background reading: flux capacitor and google group discussion.

2.3. 高可用,Zone和Regions

The Eureka server does not have a back end store, but the service instances in the registry all have to send heartbeats to keep their registrations up to date (so this can be done in memory). Clients also have an in-memory cache of Eureka registrations (so they do not have to go to the registry for every request to a service).

Eureka服务器没有后端存储,但是注册中心中的服务实例都必须发送心跳来保持注册的最新状态(因此这可以在内存中完成)。客户端也有一个Eureka注册的内存缓存(因此他们不必为每个服务请求去注册中心)。

By default, every Eureka server is also a Eureka client and requires (at least one) service URL to locate a peer. If you do not provide it, the service runs and works, but it fills your logs with a lot of noise about not being able to register with the peer.

默认情况下,每个Eureka服务器也是一个Eureka客户机,并且需要(至少一个)服务URL来定位对等点。如果你不提供它,服务会运行和工作,但它会用大量关于不能注册到对等点的干扰信息填满你的日志。

See also below for details of Ribbon support on the client side for Zones and Regions.
还请参阅下面有关客户端对区域和区域的功能区支持的详细信息。

2.4.独立模式

The combination of the two caches (client and server) and the heartbeats make a standalone Eureka server fairly resilient to failure, as long as there is some sort of monitor or elastic runtime (such as Cloud Foundry) keeping it alive. In standalone mode, you might prefer to switch off the client side behavior so that it does not keep trying and failing to reach its peers. The following example shows how to switch off the client-side behavior:

两个缓存(客户端和服务器)和心跳的结合使独立的Eureka服务器具有相当强的抗故障能力,只要有某种监视器或弹性运行时(如Cloud Foundry)使其保持活动状态。在独立模式下,您可能更倾向于关闭客户端行为,这样它就不会一直尝试并无法到达它的peers。下面的例子展示了如何关闭客户端行为:

application.yml (Standalone Eureka Server)

server:
  port: 8761

eureka:
  instance:
    hostname: localhost
  client:
    registerWithEureka: false
    fetchRegistry: false
    serviceUrl:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/

Notice that the serviceUrl is pointing to the same host as the local instance.
请注意,serviceUrl指向与本地实例相同的主机。

2.5.peer感知

Eureka can be made even more resilient and available by running multiple instances and asking them to register with each other. In fact, this is the default behavior, so all you need to do to make it work is add a valid serviceUrl to a peer, as shown in the following example:

通过运行多个实例并要求它们彼此注册,Eureka可以变得更有弹性和可用性。实际上,这是默认行为,所以要使其工作,您只需向peer添加一个有效的serviceUrl,如下面的示例所示:
application.yml (Two Peer Aware Eureka Servers)

---
spring:
  profiles: peer1
eureka:
  instance:
    hostname: peer1
  client:
    serviceUrl:
      defaultZone: https://peer2/eureka/

---
spring:
  profiles: peer2
eureka:
  instance:
    hostname: peer2
  client:
    serviceUrl:
      defaultZone: https://peer1/eureka/

In the preceding example, we have a YAML file that can be used to run the same server on two hosts (peer1 and peer2) by running it in different Spring profiles. You could use this configuration to test the peer awareness on a single host (there is not much value in doing that in production) by manipulating /etc/hosts to resolve the host names. In fact, the eureka.instance.hostname is not needed if you are running on a machine that knows its own hostname (by default, it is looked up by using java.net.InetAddress).

在前面的示例中,我们有一个YAML文件,通过在不同的Spring配置文件中运行,它可以用于在两台主机(peer1和peer2)上运行相同的服务器。通过操作/etc/hosts解析主机名,您可以使用这个配置来测试单个主机上的peer感知(在生产环境中这样做没有太大的价值)。事实上。如果您在一台知道自己主机名的机器上运行,则不需要eureka.instance.hostname(默认情况下,通过使用java.net.InetAddress查找)。

You can add multiple peers to a system, and, as long as they are all connected to each other by at least one edge, they synchronize the registrations amongst themselves. If the peers are physically separated (inside a data center or between multiple data centers), then the system can, in principle, survive “split-brain” type failures. You can add multiple peers to a system, and as long as they are all directly connected to each other, they will synchronize the registrations amongst themselves.

您可以向一个系统添加多个对等点,只要它们通过至少一条边相互连接,它们就可以在彼此之间同步注册。如果对等点在物理上是分开的(在一个数据中心内或在多个数据中心之间),那么系统原则上可以在“split-brain”类型的故障中存活下来。您可以向一个系统添加多个对等点,只要它们都是直接相互连接的,它们之间就会同步注册。

application.yml (Three Peer Aware Eureka Servers)

eureka:
  client:
    serviceUrl:
      defaultZone: https://peer1/eureka/,http://peer2/eureka/,http://peer3/eureka/

---
spring:
  profiles: peer1
eureka:
  instance:
    hostname: peer1

---
spring:
  profiles: peer2
eureka:
  instance:
    hostname: peer2

---
spring:
  profiles: peer3
eureka:
  instance:
    hostname: peer3

2.6.何时prefer IP Address

In some cases, it is preferable for Eureka to advertise the IP addresses of services rather than the hostname. Set eureka.instance.preferIpAddress to true and, when the application registers with eureka, it uses its IP address rather than its hostname.

在某些情况下,Eureka最好公布服务的IP地址,而不是主机名。设置eureka.instance.preferIpAddresstrue当应用程序注册到eureka时,它使用它的IP地址而不是主机名。

If the hostname cannot be determined by Java, then the IP address is sent to Eureka. Only explict way of setting the hostname is by setting eureka.instance.hostname property. You can set your hostname at the run-time by using an environment variable — for example, eureka.instance.hostname=${HOST_NAME}.

如果主机名不能由Java确定,那么IP地址将被发送到Eureka。设置主机名的唯一方法是设置eureka.instance.hostname。您可以在运行时通过使用环境变量设置您的主机名—例如,eureka.instance.hostname=${HOST_NAME}

2.7. 保护Eureka Server

You can secure your Eureka server simply by adding Spring Security to your server’s classpath via spring-boot-starter-security. By default when Spring Security is on the classpath it will require that a valid CSRF token be sent with every request to the app. Eureka clients will not generally possess a valid cross site request forgery (CSRF) token you will need to disable this requirement for the /eureka/** endpoints. For example:

您只需通过spring-boot-starter-security将Spring Security 添加到服务器的类路径,就可以保护Eureka服务器。默认情况下,当Spring Security在类路径上时,它将要求每个请求都发送一个有效的CSRF令牌。Eureka客户端通常不会拥有一个有效的跨站点请求伪造(CSRF)令牌,你需要禁用/ Eureka /**端点的这个要求。例如:

@EnableWebSecurity
class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().ignoringAntMatchers("/eureka/**");
        super.configure(http);
    }
}

For more information on CSRF see the Spring Security documentation.

A demo Eureka Server can be found in the Spring Cloud Samples repo.

2.8. 使Eureka Server和Client启动器时禁用Ribbon

spring-cloud-starter-netflix-eureka-server and spring-cloud-starter-netflix-eureka-client come along with a spring-cloud-starter-netflix-ribbon. Since Ribbon load-balancer is now in maintenance mode, we suggest switching to using the Spring Cloud LoadBalancer, also included in Eureka starters, instead.

spring-cloud-starter-netflix-eureka-serverspring-cloud-starter-netflix-eureka-client附带了spring-cloud-starter-netflix-ribbon。由于功能区负载均衡器现在处于维护模式,我们建议转而使用Spring Cloud LoadBalancer,Eureka启动器中也包含这个负载均衡器。

In order to that, you can set the value of spring.cloud.loadbalancer.ribbon.enabled property to false.

为此,你可以设置spring.cloud.loadbalancer.ribbon.enabled的属性变为false

You can then also exclude ribbon-related dependencies from Eureka starters in your build files, like so:
你也可以在你的pom文件中排除ribbon相关依赖。如下:

<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.cloud</groupId>
                    <artifactId>spring-cloud-starter-ribbon</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.netflix.ribbon</groupId>
                    <artifactId>ribbon-eureka</artifactId>
                </exclusion>
            </exclusions>
</dependency>

2.9.JDK11支持

The JAXB modules which the Eureka server depends upon were removed in JDK 11. If you intend to use JDK 11 when running a Eureka server you must include these dependencies in your POM or Gradle file.

Eureka服务器所依赖的JAXB模块在JDK 11中被删除。如果您打算在运行Eureka服务器时使用JDK 11,则必须在POM或Gradle文件中包含这些依赖项。

<dependency>
    <groupId>org.glassfish.jaxb</groupId>
    <artifactId>jaxb-runtime</artifactId>
</dependency>

3.断路器:使用Hystrix的Spring Cloud断路器

3.1.禁用Spring Cloud断路器Hystrix

You can disable the auto-configuration by setting spring.cloud.circuitbreaker.hystrix.enabled to false.

3.2.配置Hystrix断路器

3.2.1默认配置

To provide a default configuration for all of your circuit breakers create a Customize bean that is passed a HystrixCircuitBreakerFactory or ReactiveHystrixCircuitBreakerFactory. The configureDefault method can be used to provide a default configuration.

要为你所有的断路器提供默认配置,创建一个Customizebean,它通过HystrixCircuitBreakerFactoryReactiveHystrixCircuitBreakerFactory传递。configureDefault方法可用于提供默认配置。

@Bean
public Customizer<HystrixCircuitBreakerFactory> defaultConfig() {
    return factory -> factory.configureDefault(id -> HystrixCommand.Setter
            .withGroupKey(HystrixCommandGroupKey.Factory.asKey(id))
            .andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
            .withExecutionTimeoutInMilliseconds(4000)));
}

Reactive Example

@Bean
public Customizer<ReactiveHystrixCircuitBreakerFactory> defaultConfig() {
    return factory -> factory.configureDefault(id -> HystrixObservableCommand.Setter
            .withGroupKey(HystrixCommandGroupKey.Factory.asKey(id))
            .andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
                    .withExecutionTimeoutInMilliseconds(4000)));
}

3.2.2特定配置

Similarly to providing a default configuration, you can create a Customize bean this is passed a HystrixCircuitBreakerFactory

与提供默认配置类似,您可以创建一个通过HystrixCircuitBreakerFactory传递的自定义bean。

@Bean
public Customizer<HystrixCircuitBreakerFactory> customizer() {
    return factory -> factory.configure(builder -> builder.commandProperties(
                    HystrixCommandProperties.Setter().withExecutionTimeoutInMilliseconds(2000)), "foo", "bar");
}

Reactive Example

@Bean
public Customizer<ReactiveHystrixCircuitBreakerFactory> customizer() {
    return factory -> factory.configure(builder -> builder.commandProperties(
                    HystrixCommandProperties.Setter().withExecutionTimeoutInMilliseconds(2000)), "foo", "bar");
}

4.断路器:Hystrix客户端

Netflix has created a library called Hystrix that implements the circuit breaker pattern. In a microservice architecture, it is common to have multiple layers of service calls, as shown in the following example:

Netflix创建了一个名为Hystrix的库,它实现了断路器模式。在微服务体系结构中,通常会有多层服务调用,如下面的例子所示:
Figure 1. Microservice Graph
Figure 1. Microservice Graph

A service failure in the lower level of services can cause cascading failure all the way up to the user. When calls to a particular service exceed circuitBreaker.requestVolumeThreshold (default: 20 requests) and the failure percentage is greater than circuitBreaker.errorThresholdPercentage (default: >50%) in a rolling window defined by metrics.rollingStats.timeInMilliseconds (default: 10 seconds), the circuit opens and the call is not made. In cases of error and an open circuit, a fallback can be provided by the developer.

较低级别服务中的服务故障可能会导致向上直到用户的级联故障。在由metrics.rollingStats.timeInMilliseconds(默认为10秒)定义的滚动窗口中,当对特定服务的调用超过circuitBreaker.requestVolumeThreshold(缺省值:20个请求)并且失败百分比大于circuitBreaker.errorThresholdPercentage(默认值为50%)时,回路断开,调用不进行。在出现错误和开路的情况下,开发人员可以提供回退。

在这里插入图片描述
Figure 2. Hystrix 回退防止级联故障

Having an open circuit stops cascading failures and allows overwhelmed or failing services time to recover. The fallback can be another Hystrix protected call, static data, or a sensible empty value. Fallbacks may be chained so that the first fallback makes some other business call, which in turn falls back to static data.

采用开路电路可以停止级联故障,并允许过载或故障服务有时间恢复。回退可以是另一个Hystrix保护调用、静态数据或合理的空值。可以对回退进行链接,以便第一个回退进行一些其他业务调用,这些业务调用将返回到静态数据。

4.1.引入Hystrix

To include Hystrix in your project, use the starter with a group ID of org.springframework.cloud and a artifact ID of spring-cloud-starter-netflix-hystrix. See the Spring Cloud Project page for details on setting up your build system with the current Spring Cloud Release Train.

<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-netflix-hystrix -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
    <version>2.2.4.RELEASE</version>
</dependency>

The following example shows a minimal Eureka server with a Hystrix circuit breaker:

@SpringBootApplication
@EnableCircuitBreaker
public class Application {

    public static void main(String[] args) {
        new SpringApplicationBuilder(Application.class).web(true).run(args);
    }

}

@Component
public class StoreIntegration {

    @HystrixCommand(fallbackMethod = "defaultStores")
    public Object getStores(Map<String, Object> parameters) {
        //do stuff that might fail
    }

    public Object defaultStores(Map<String, Object> parameters) {
        return /* something useful */;
    }
}

The @HystrixCommand is provided by a Netflix contrib library called “javanica”. Spring Cloud automatically wraps Spring beans with that annotation in a proxy that is connected to the Hystrix circuit breaker. The circuit breaker calculates when to open and close the circuit and what to do in case of a failure.

@HystrixCommand是由一个名为“javanica”的Netflix发明库提供的。Spring Cloud自动将带有该注释的Spring bean包装在一个连接到Hystrix断路器的代理中。断路器计算何时打开和关闭电路,以及在失败的情况下做什么。

To configure the @HystrixCommand you can use the commandProperties attribute with a list of @HystrixProperty annotations. See here for more details. See the Hystrix wiki for details on the properties available.

要配置@HystrixCommand,可以使用commandProperties属性和一列@HystrixProperty注释。更多细节请看这里。有关可用属性的详细信息,请参阅Hystrix wiki。

4.2. 传播安全上下文或使用Spring Scope

If you want some thread local context to propagate into a @HystrixCommand, the default declaration does not work, because it executes the command in a thread pool (in case of timeouts). You can switch Hystrix to use the same thread as the caller through configuration or directly in the annotation, by asking it to use a different “Isolation Strategy”. The following example demonstrates setting the thread in the annotation:

如果您希望将某个线程本地上下文传播到@HystrixCommand中,则默认声明不起作用,因为它在线程池中执行该命令(在超时的情况下)。通过配置或直接在注释中要求Hystrix使用不同的“隔离策略”,您可以切换Hystrix来使用与调用者相同的线程。下面的例子演示了如何在注释中设置线程:

@HystrixCommand(fallbackMethod = "stubMyService",
    commandProperties = {
      @HystrixProperty(name="execution.isolation.strategy", value="SEMAPHORE")
    }
)
...

The same thing applies if you are using @SessionScope or @RequestScope. If you encounter a runtime exception that says it cannot find the scoped context, you need to use the same thread.

如果您使用的是@SessionScope@RequestScope,情况也是如此。如果遇到运行时异常,表示无法找到作用域上下文,则需要使用相同的线程。

You also have the option to set the hystrix.shareSecurityContext property to true. Doing so auto-configures a Hystrix concurrency strategy plugin hook to transfer the SecurityContext from your main thread to the one used by the Hystrix command. Hystrix does not let multiple Hystrix concurrency strategy be registered so an extension mechanism is available by declaring your own HystrixConcurrencyStrategy as a Spring bean. Spring Cloud looks for your implementation within the Spring context and wrap it inside its own plugin.

您还可以选择设置hystrix.shareSecurityContext属性为true。这样做会自动配置Hystrix并发策略插件挂钩,以将SecurityContext从主线线程传输到Hystrix命令使用的线程中。Hystrix不允许注册多个Hystrix并发策略,因此可以通过将自己的HystrixConcurrencyStrategy声明为一个Spring bean来获得扩展机制。Spring Cloud在Spring上下文中寻找您的实现,并将其包装在自己的插件中。

4.3. 健康指标

The state of the connected circuit breakers are also exposed in the /health endpoint of the calling application, as shown in the following example:

连接的断路器的状态也暴露在调用应用程序的/health端点中,如下面的示例所示:

{
    "hystrix": {
        "openCircuitBreakers": [
            "StoreIntegration::getStoresByLocationLink"
        ],
        "status": "CIRCUIT_OPEN"
    },
    "status": "UP"
}

4.4.Hystrix指标流

To enable the Hystrix metrics stream, include a dependency on spring-boot-starter-actuator and set management.endpoints.web.exposure.include: hystrix.stream. Doing so exposes the /actuator/hystrix.stream as a management endpoint, as shown in the following example:

要启用Hystrix指标流,需要包含spring-boot-starter-actuator 的依赖,并设置management.endpoints.web.exposure.include: hystrix.stream。这样做将暴露 /actuator/hystrix.stream作为管理端点,如下面的例子所示:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

5.断路器:Hystrix Dashboard

One of the main benefits of Hystrix is the set of metrics it gathers about each HystrixCommand. The Hystrix Dashboard displays the health of each circuit breaker in an efficient manner.

Hystrix的主要优点之一是它收集了关于每个HystrixCommand的一组度量。Hystrix Dashboard 以有效的方式显示每个断路器的运行状况。
在这里插入图片描述
Figure 3. Hystrix Dashboard

6.Hystrix 超时设定和 Ribbon Clients

When using Hystrix commands that wrap Ribbon clients you want to make sure your Hystrix timeout is configured to be longer than the configured Ribbon timeout, including any potential retries that might be made. For example, if your Ribbon connection timeout is one second and the Ribbon client might retry the request three times, than your Hystrix timeout should be slightly more than three seconds.

当使用Hystrix命令包装Ribbon客户端时,您希望确保Hystrix超时配置为比配置的Ribbon超时更长,包括可能进行的任何重试。例如,如果您的Ribbon连接超时时间是1秒,而Ribbon客户端可能重试请求三次,那么Hystrix超时时间应该略大于3秒。

6.1. 引入Hystrix Dashboard

To include the Hystrix Dashboard in your project, use the starter with a group ID of org.springframework.cloud and an artifact ID of spring-cloud-starter-netflix-hystrix-dashboard. See the Spring Cloud Project page for details on setting up your build system with the current Spring Cloud Release Train.

<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-netflix-hystrix-dashboard -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
    <version>2.2.4.RELEASE</version>
</dependency>

To run the Hystrix Dashboard, annotate your Spring Boot main class with @EnableHystrixDashboard. Then visit /hystrix and point the dashboard to an individual instance’s /hystrix.stream endpoint in a Hystrix client application.

When connecting to a /hystrix.stream endpoint that uses HTTPS, the certificate used by the server must be trusted by the JVM. If the certificate is not trusted, you must import the certificate into the JVM in order for the Hystrix Dashboard to make a successful connection to the stream endpoint.

当使用HTTPS连接到/hystrix.stream 端点时,服务器使用的证书必须由JVM信任。如果证书不受信任,您必须将证书导入到JVM中,以便Hystrix仪表板能够成功地连接到流端点。

In order to use the /proxy.stream endpoint you must configure a list of hosts to allow connections to. To set the list of allowed hosts use hystrix.dashboard.proxyStreamAllowList. You can use an Ant-style pattern in the host name to match against a wider range of host names.

为了使用 /proxy.stream端点,你必须配置主机列表以允许连接。使用hystrix.dashboard.proxyStreamAllowList设置允许的主机列表。您可以在主机名中使用Ant-style的模式来匹配更广泛的主机名。

6.2.Turbine

Looking at an individual instance’s Hystrix data is not very useful in terms of the overall health of the system. Turbine is an application that aggregates all of the relevant /hystrix.stream endpoints into a combined /turbine.stream for use in the Hystrix Dashboard. Individual instances are located through Eureka. Running Turbine requires annotating your main class with the @EnableTurbine annotation (for example, by using spring-cloud-starter-netflix-turbine to set up the classpath). All of the documented configuration properties from the Turbine 1 wiki apply. The only difference is that the turbine.instanceUrlSuffix does not need the port prepended, as this is handled automatically unless turbine.instanceInsertPort=false.

就系统的总体健康状况而言,查看单个实例的Hystrix数据并不是很有用。Turbine 是一个应用程序,聚合了所有相关/hystrix.stream端点进入联合的 /turbine.stream,以便在Hystrix仪表板中使用。单个实例通过Eureka定位。运行Turbine需要使用@EnableTurbine 注解您的主类(例如,通过使用spring-cloud-starter-netflix-turbine来设置类路径)。 Turbine 1 wiki apply中所有文档化的配置属性都适用。唯一的区别是turbine.instanceUrlSuffix 不需要预先设置的端口,因为这是自动处理的,除非turbine.instanceInsertPort=false.

By default, Turbine looks for the /hystrix.stream endpoint on a registered instance by looking up its hostName and port entries in Eureka and then appending /hystrix.stream to it. If the instance’s metadata contains management.port, it is used instead of the port value for the /hystrix.stream endpoint. By default, the metadata entry called management.port is equal to the management.port configuration property. It can be overridden though with following configuration:

默认情况下,Turbine采用在Eureka中查找其主机名和端口条目的方式,在已注册实例上查找寻找 /hystrix.stream 端点,然后附加上 /hystrix.stream。如果实例的元数据包含 management.port,它被用来代替 /hystrix.stream 的端口值。默认情况下,被称为management.port的元数据条目等于 management.port 配置属性。它可以被覆盖通过以下配置:

eureka:
  instance:
    metadata-map:
      management.port: ${management.port:8081}

The turbine.appConfig configuration key is a list of Eureka serviceIds that turbine uses to lookup instances. The turbine stream is then used in the Hystrix dashboard with a URL similar to the following:

turbine.appConfig配置键是涡轮用于查找实例的Eureka serviceid列表。 turbine stream然后在Hystrix仪表盘使用一个类似的URL如下:

my.turbine.server:8080/turbine.stream?cluster=CLUSTERNAME

The cluster parameter can be omitted if the name is default. The cluster parameter must match an entry in turbine.aggregator.clusterConfig. Values returned from Eureka are upper-case. Consequently, the following example works if there is an application called customers registered with Eureka:

如果名称为“default”,则可以省略集群参数。“cluster”参数必须与“turbine.aggregator.clusterConfig”中的条目匹配。从Eureka返回的值是大写的。因此,如果有一个叫做“customers”的应用程序注册了Eureka,下面的例子就可以工作了:

turbine:
  aggregator:
    clusterConfig: CUSTOMERS
  appConfig: customers

If you need to customize which cluster names should be used by Turbine (because you do not want to store cluster names in turbine.aggregator.clusterConfig configuration), provide a bean of type TurbineClustersProvider.

如果你需要定制哪个集群名称应该被Turbine 使用(因为你不希望存储集群名称’ Turbine .aggregator.clusterConfig ' configuration),提供类型为’ TurbineClustersProvider '的bean。

The clusterName can be customized by a SPEL expression in turbine.clusterNameExpression with root as an instance of InstanceInfo. The default value is appName, which means that the Eureka serviceId becomes the cluster key (that is, the InstanceInfo for customers has an appName of CUSTOMERS). A different example is turbine.clusterNameExpression=aSGName, which gets the cluster name from the AWS ASG name. The following listing shows another example:

clusterName”可以通过“turbine.clusterNameExpression”中的SPEL表达式自定义,用root作为InstanceInfo的实例。默认值是appName,这意味着Eureka serviceId 成为集群键(也就是说,用于客户的 InstanceInfo 具有’ customersappName )。另一个不同的例子是“turbine.clusterNameExpression=aSGName’,它从AWS ASG名称中获取集群名称。下面的清单显示了另一个例子:

turbine:
  aggregator:
    clusterConfig: SYSTEM,USER
  appConfig: customers,stores,ui,admin
  clusterNameExpression: metadata['cluster']

In the preceding example, the cluster name from four services is pulled from their metadata map and is expected to have values that include SYSTEM and USER.

在前面的示例中,四个服务的集群名是从它们的元数据映射中提取的,并且预期其值包括SYSTEM和USER

To use the “default” cluster for all apps, you need a string literal expression (with single quotes and escaped with double quotes if it is in YAML as well):

为所有应用使用“default”集群,你需要一个字符串字面表达式(单引号和转义双引号,如果它在YAML中也是):

turbine:
  appConfig: customers,stores
  clusterNameExpression: "'default'"

Spring Cloud provides a spring-cloud-starter-netflix-turbine that has all the dependencies you need to get a Turbine server running. To add Turbine, create a Spring Boot application and annotate it with @EnableTurbine.

Spring Cloud提供了 spring-cloud-starter-netflix-turbine ,它拥有运行Turbine服务所需的所有依赖项。要添加 Turbine,请创建一个Spring引导应用程序并使用@EnableTurbine对其进行注释。

By default, Spring Cloud lets Turbine use the host and port to allow multiple processes per host, per cluster. If you want the native Netflix behavior built into Turbine to not allow multiple processes per host, per cluster (the key to the instance ID is the hostname), set turbine.combineHostPort=false.

默认情况下,Spring Cloud允许Turbine使用主机和端口来允许每个主机和每个集群有多个进程。如果您想让Turbine内建的本地Netflix行为不允许每个主机、每个集群有多个进程(实例ID的关键是主机名),那么设置turbine.combineHostPort=false.

6.2.1. 集群端点

In some situations it might be useful for other applications to know what custers have been configured in Turbine. To support this you can use the /clusters endpoint which will return a JSON array of all the configured clusters.

在某些情况下,其他应用程序知道什么集群已配置在Turbine可能很有用。要支持这一点,可以使用’ /clusters 端点,它将返回所有配置集群的JSON数组。
GET /clusters

[
  {
    "name": "RACES",
    "link": "http://localhost:8383/turbine.stream?cluster=RACES"
  },
  {
    "name": "WEB",
    "link": "http://localhost:8383/turbine.stream?cluster=WEB"
  }
]

This endpoint can be disabled by setting turbine.endpoints.clusters.enabled to false.

6.3.Turbine Stream

In some environments (such as in a PaaS setting), the classic Turbine model of pulling metrics from all the distributed Hystrix commands does not work. In that case, you might want to have your Hystrix commands push metrics to Turbine. Spring Cloud enables that with messaging. To do so on the client, add a dependency to spring-cloud-netflix-hystrix-stream and the spring-cloud-starter-stream-* of your choice. See the Spring Cloud Stream documentation for details on the brokers and how to configure the client credentials. It should work out of the box for a local broker.

在某些环境中(例如PaaS设置),从所有分布式Hystrix命令提取指标的经典Turbine模型不起作用。在这种情况下,你可能想要你的Hystrix命令推动指标Turbine。Spring Cloud通过消息传递实现了这一点。要在客户端上执行此操作,需要向spring-cloud-netflix-hystrix-stream和您选择的spring-cloud-starter-stream-*添加一个依赖项。有关代理和如何配置客户端凭据的详细信息,请参阅Spring Cloud Stream文档。对于本地的代理人来说,这应该是开箱即用的。

On the server side, create a Spring Boot application and annotate it with @EnableTurbineStream. The Turbine Stream server requires the use of Spring Webflux, therefore spring-boot-starter-webflux needs to be included in your project. By default spring-boot-starter-webflux is included when adding spring-cloud-starter-netflix-turbine-stream to your application.

在服务器端,创建一个Spring Boot应用程序并使用’ @EnableTurbineStream '注释它。Turbine流服务器需要使用Spring Webflux,因此“Spring -boot-starter- Webflux”需要包括在你的项目中。在你的应用程序中添加“spring-cloud-starter-netflix-turbine-stream”时,就会包含spring-boot-starter-webflux

You can then point the Hystrix Dashboard to the Turbine Stream Server instead of individual Hystrix streams. If Turbine Stream is running on port 8989 on myhost, then put myhost:8989 in the stream input field in the Hystrix Dashboard. Circuits are prefixed by their respective serviceId, followed by a dot (.), and then the circuit name.

然后你可以将Hystrix仪表盘指向Turbine流服务,而不是单独的Hystrix流。如果涡轮流在myhost的端口8989上运行,那么在Hystrix仪表盘的流输入字段中放置’ myhost:8989 ‘。电路的前缀是各自的’ serviceId ',后跟一个点(.),然后是电路名。

Spring Cloud provides a spring-cloud-starter-netflix-turbine-stream that has all the dependencies you need to get a Turbine Stream server running. You can then add the Stream binder of your choice — such as spring-cloud-starter-stream-rabbit.

Spring Cloud提供了Spring - Cloud -starter-netflix-turbine- Stream,它拥有运行Turbine流服务器所需的所有依赖项。然后您可以添加您选择的流绑定器—例如spring-cloud-starter-stream-rabbit

Turbine Stream server also supports the cluster parameter. Unlike Turbine server, Turbine Stream uses eureka serviceIds as cluster names and these are not configurable.

Turbine流服务也支持群集参数。与Turbine服务器不同,Turbin流使用eureka serviceid作为集群名,这些是不可配置的。

If Turbine Stream server is running on port 8989 on my.turbine.server and you have two eureka serviceIds customers and products in your environment, the following URLs will be available on your Turbine Stream server. default and empty cluster name will provide all metrics that Turbine Stream server receives.

如果Turbine流服务运行在端口8989的my.turbine.server上 ,并且您有两个尤里卡服务idcustomersproducts在您的环境,以下url将在您的Turbine流服务器上可用。 default 和空集群名称将提供Turbine 流服务器接收的所有指标。

https://my.turbine.sever:8989/turbine.stream?cluster=customers
https://my.turbine.sever:8989/turbine.stream?cluster=products
https://my.turbine.sever:8989/turbine.stream?cluster=default
https://my.turbine.sever:8989/turbine.stream

So, you can use eureka serviceIds as cluster names for your Turbine dashboard (or any compatible dashboard). You don’t need to configure any properties like turbine.appConfig, turbine.clusterNameExpression and turbine.aggregator.clusterConfig for your Turbine Stream server.

因此,您可以使用eureka serviceIds作为您的Turbine仪表盘(或任何兼容的仪表盘)的集群名称。你不需要为你的Turbine 流服务配置任何属性,如’turbine.appConfig”、turbine.clusterNameExpressionturbine.aggregator.clusterConfig

Turbine Stream server gathers all metrics from the configured input channel with Spring Cloud Stream. It means that it doesn’t gather Hystrix metrics actively from each instance. It just can provide metrics that were already gathered into the input channel by each instance.

Turbine 流服务器从配置的输入通道收集所有指标与Spring Cloud Stream。这意味着它不会主动从每个实例收集Hystrix指标。它只能提供每个实例已经收集到输入通道中的指标。

7.客户端负载均衡: Ribbon

Ribbon is a client-side load balancer that gives you a lot of control over the behavior of HTTP and TCP clients. Feign already uses Ribbon, so, if you use @FeignClient, this section also applies.

Ribbon是一个客户端负载平衡器,它为您提供了对HTTP和TCP客户机行为的大量控制。Feign已经使用了Ribbon,所以,如果你使用“@FeignClient”,这个部分也适用。

A central concept in Ribbon is that of the named client. Each load balancer is part of an ensemble of components that work together to contact a remote server on demand, and the ensemble has a name that you give it as an application developer (for example, by using the @FeignClient annotation). On demand, Spring Cloud creates a new ensemble as an ApplicationContext for each named client by using RibbonClientConfiguration. This contains (amongst other things) an ILoadBalancer, a RestClient, and a ServerListFilter.

Ribbon的核心概念是命名客户端。每个负载平衡器都是一个组件集合的一部分,这些组件一起工作,按需联系远程服务器,并且这个集合有一个您作为应用程序开发人员给它的名称(例如,通过使用@FeignClient注释)。根据需要,Spring Cloud使用RibbonClientConfiguration为每个命名的客户机创建一个新的集成作为一个ApplicationContext。其中包括一个ILoadBalancer、一个RestClient和一个ServerListFilter

7.1. How to Include Ribbon

To include Ribbon in your project, use the starter with a group ID of org.springframework.cloud and an artifact ID of spring-cloud-starter-netflix-ribbon. See the Spring Cloud Project page for details on setting up your build system with the current Spring Cloud Release Train.

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

7.2. 定制Ribbon Client

You can configure some bits of a Ribbon client by using external properties in <client>.ribbon.*, which is similar to using the Netflix APIs natively, except that you can use Spring Boot configuration files. The native options can be inspected as static fields in CommonClientConfigKey (part of ribbon-core).

您可以通过在<client>.ribbon.*中使用外部属性来配置一些Ribbon客户端,这类似于原生使用Netflix api,只是可以使用SpringBoot配置文件。原生选项可以在CommonClientConfigKey(part of ribbon-core)中作为静态字段检查。

Spring Cloud also lets you take full control of the client by declaring additional configuration (on top of the RibbonClientConfiguration) using @RibbonClient, as shown in the following example:

Spring Cloud还允许您通过使用@RibbonClient声明额外的配置(在RibbonClientConfiguration之上)来完全控制客户端,如下面的例子所示:

@Configuration
@RibbonClient(name = "custom", configuration = CustomConfiguration.class)
public class TestConfiguration {
}

In this case, the client is composed from the components already in RibbonClientConfiguration, together with any in CustomConfiguration (where the latter generally overrides the former).

在这种情况下,客户端是由“RibbonClientConfiguration”中已经存在的组件和“CustomConfiguration”中的组件组成的(后者通常会覆盖前者)。

The CustomConfiguration class must be a @Configuration class, but take care that it is not in a @ComponentScan for the main application context. Otherwise, it is shared by all the @RibbonClients. If you use @ComponentScan (or @SpringBootApplication), you need to take steps to avoid it being included (for instance, you can put it in a separate, non-overlapping package or specify the packages to scan explicitly in the @ComponentScan).

CustomConfiguration类必须是@Configuration类,但是要注意它不在主应用程序上下文的@ComponentScan中。否则,它将被所有的@RibbonClients共享。如果使用@ComponentScan(或@SpringBootApplication),则需要采取步骤避免包含它(例如,可以将其放在一个单独的、不重叠的包中,或者在@ComponentScan中指定要显式扫描的包)

The following table shows the beans that Spring Cloud Netflix provides by default for Ribbon:

Bean TypeBean NameClass Name
IClientConfigribbonClientConfigDefaultClientConfigImpl
IRuleribbonRuleZoneAvoidanceRule
IPingribbonPingDummyPing
ServerList< Server >ribbonServerListConfigurationBasedServerList
ServerListFilter< Server>ribbonServerListFilterZonePreferenceServerListFilter
ILoadBalancerribbonLoadBalancerZoneAwareLoadBalancer
ServerListUpdaterribbonServerListUpdaterPollingServerListUpdater

Creating a bean of one of those type and placing it in a @RibbonClient configuration (such as FooConfiguration above) lets you override each one of the beans described, as shown in the following example:

创建其中一种类型的bean,并将其放在’ @RibbonClient '配置中(如上面的FooConfiguration),可以让您覆盖所描述的每个bean,如下面的示例所示:

@Configuration(proxyBeanMethods = false)
protected static class FooConfiguration {

    @Bean
    public ZonePreferenceServerListFilter serverListFilter() {
        ZonePreferenceServerListFilter filter = new ZonePreferenceServerListFilter();
        filter.setZone("myTestZone");
        return filter;
    }

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

}

The include statement in the preceding example replaces NoOpPing with PingUrl and provides a custom serverListFilter.

前面示例中的include语句用PingUrl替换了NoOpPing,并提供了一个自定义serverListFilter

7.3. 自定义所有Ribbon Clients的默认配置

A default configuration can be provided for all Ribbon Clients by using the @RibbonClients annotation and registering a default configuration, as shown in the following example:

通过使用@RibbonClients 注释并注册一个默认配置,可以为所有的Ribbon客户端提供一个默认配置,如下所示:

@RibbonClients(defaultConfiguration = DefaultRibbonConfig.class)
public class RibbonClientDefaultConfigurationTestsConfig {

    public static class BazServiceList extends ConfigurationBasedServerList {

        public BazServiceList(IClientConfig config) {
            super.initWithNiwsConfig(config);
        }

    }

}

@Configuration(proxyBeanMethods = false)
class DefaultRibbonConfig {

    @Bean
    public IRule ribbonRule() {
        return new BestAvailableRule();
    }

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

    @Bean
    public ServerList<Server> ribbonServerList(IClientConfig config) {
        return new RibbonClientDefaultConfigurationTestsConfig.BazServiceList(config);
    }

    @Bean
    public ServerListSubsetFilter serverListFilter() {
        ServerListSubsetFilter filter = new ServerListSubsetFilter();
        return filter;
    }

}

7.4.通过设置属性定制Ribbon Client

Starting with version 1.2.0, Spring Cloud Netflix now supports customizing Ribbon clients by setting properties to be compatible with the Ribbon documentation.

This lets you change behavior at start up time in different environments.

The following list shows the supported properties>:

  • <clientName>.ribbon.NFLoadBalancerClassName: Should implement ILoadBalancer

  • <clientName>.ribbon.NFLoadBalancerRuleClassName: Should implement IRule

  • <clientName>.ribbon.NFLoadBalancerPingClassName: Should implement IPing

  • .ribbon.NIWSServerListClassName: Should implement ServerList

  • <clientName>.ribbon.NIWSServerListFilterClassName: Should implement ServerListFilter

Classes defined in these properties have precedence over beans defined by using @RibbonClient(configuration=MyRibbonConfig.class) and the defaults provided by Spring Cloud Netflix.

在这些属性中定义的类优先于使用@RibbonClient(configuration=MyRibbonConfig.class)和Spring Cloud Netflix提供的默认值定义的bean。

To set the IRule for a service name called users, you could set the following properties:

application.yml

users:
  ribbon:
    NIWSServerListClassName: com.netflix.loadbalancer.ConfigurationBasedServerList
    NFLoadBalancerRuleClassName: com.netflix.loadbalancer.WeightedResponseTimeRule

See the Ribbon documentation for implementations provided by Ribbon.

7.5.和Eureka一起用Ribbon

When Eureka is used in conjunction with Ribbon (that is, both are on the classpath), the ribbonServerList is overridden with an extension of DiscoveryEnabledNIWSServerList, which populates the list of servers from Eureka. It also replaces the IPing interface with NIWSDiscoveryPing, which delegates to Eureka to determine if a server is up. The ServerList that is installed by default is a DomainExtractingServerList. Its purpose is to make metadata available to the load balancer without using AWS AMI metadata (which is what Netflix relies on). By default, the server list is constructed with “zone” information, as provided in the instance metadata (so, on the remote clients, set eureka.instance.metadataMap.zone). If that is missing and if the approximateZoneFromHostname flag is set, it can use the domain name from the server hostname as a proxy for the zone. Once the zone information is available, it can be used in a ServerListFilter. By default, it is used to locate a server in the same zone as the client, because the default is a ZonePreferenceServerListFilter. By default, the zone of the client is determined in the same way as the remote instances (that is, through eureka.instance.metadataMap.zone).

当Eureka与Ribbon一起使用时(也就是说,两者都在类路径上),ribbonServerListDiscoveryEnabledNIWSServerList的扩展覆盖,它填充来自Eureka的服务器列表。它还将IPing接口替换为NIWSDiscoveryPing,它委托Eureka来确定服务器是否已启动。默认安装的ServerList是一个DomainExtractingServerList。它的目的是让负载平衡器在不使用AWS AMI元数据(Netflix所依赖的元数据)的情况下使用元数据。默认情况下,服务器列表是用实例元数据中提供的“区域”信息构造的(因此,在远程客户端上设置eureka.instance.metadataMap.zone)。如果缺少该区域,并且设置了approximateZoneFromHostname标志,则可以使用来自服务器主机名的域名作为区域的代理。一旦区域信息可用,就可以在ServerListFilter中使用它。默认情况下,它用于在与客户机相同的区域中定位服务器,因为默认情况下是ZonePreferenceServerListFilter。默认情况下,客户端区域的确定方式与远程实例相同(即通过eureka.instance.metadataMap.zone)

The orthodox “archaius” way to set the client zone is through a configuration property called “@zone”. If it is available, Spring Cloud uses that in preference to all other settings (note that the key must be quoted in YAML configuration).

传统的“archaius”方法是通过一个名为“@zone”的配置属性设置客户端区域。
如果它可用,Spring Cloud优先使用该设置,而不是其他所有设置(注意,在YAML配置中密钥必须用引号括起来)。

If there is no other source of zone data, then a guess is made, based on the client configuration (as opposed to the instance configuration). We take eureka.client.availabilityZones, which is a map from region name to a list of zones, and pull out the first zone for the instance’s own region (that is, the eureka.client.region, which defaults to “us-east-1”, for compatibility with native Netflix).

如果没有其他来源的区域数据,则根据客户端配置(而不是实例配置)进行猜测。我们使用eureka.client.availabilityZones,它是一个从区域名称到区域列表的映射,并为实例自己的region(即eureka.client.region,默认为“us-east-1”,以与本地Netflix兼容)提取第一个区域。

7.6. 示例:怎样在没有Eureka的情况下使用Ribbon

Eureka is a convenient way to abstract the discovery of remote servers so that you do not have to hard code their URLs in clients. However, if you prefer not to use Eureka, Ribbon and Feign also work. Suppose you have declared a @RibbonClient for “stores”, and Eureka is not in use (and not even on the classpath). The Ribbon client defaults to a configured server list. You can supply the configuration as follows:

Eureka是一种抽象远程服务器发现的便利方法,这样您就不必在客户机中硬编码它们的url。然而,如果你不喜欢使用Eureka, Ribbon和Feign也可以。假设您已经为“stores”声明了一个@RibbonClient,而Eureka没有被使用(甚至在类路径中也没有)。Ribbon客户端默认是一个已配置的服务器列表。您可以提供如下配置:

application.yml

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

7.7. 示例:在Ribbon中禁用Eureka

Setting the ribbon.eureka.enabled property to false explicitly disables the use of Eureka in Ribbon, as shown in the following example:
application.yml

ribbon:
  eureka:
   enabled: false

7.8. 直接使用 Ribbon API

You can also use the LoadBalancerClient directly, as shown in the following example:

public class MyClass {
    @Autowired
    private LoadBalancerClient loadBalancer;

    public void doStuff() {
        ServiceInstance instance = loadBalancer.choose("stores");
        URI storesUri = URI.create(String.format("https://%s:%s", instance.getHost(), instance.getPort()));
        // ... do something with the URI
    }
}

7.9. Ribbon 配置的缓存

Each Ribbon named client has a corresponding child application Context that Spring Cloud maintains. This application context is lazily loaded on the first request to the named client. This lazy loading behavior can be changed to instead eagerly load these child application contexts at startup, by specifying the names of the Ribbon clients, as shown in the following example:

每个名为client的功能区都有Spring Cloud维护的对应子应用程序上下文。这个应用程序上下文在第一次请求命名客户机时被延迟加载。通过指定Ribbon客户端名称,可以将这种延迟加载行为改为在启动时快速加载这些子应用程序上下文,如下面的例子所示:

application.yml

ribbon:
  eager-load:
    enabled: true
    clients: client1, client2, client3

7.10. 怎样配置 Hystrix 线程池

If you change zuul.ribbonIsolationStrategy to THREAD, the thread isolation strategy for Hystrix is used for all routes. In that case, the HystrixThreadPoolKey is set to RibbonCommand as the default. It means that HystrixCommands for all routes are executed in the same Hystrix thread pool. This behavior can be changed with the following configuration:

对于THREAD,如果你改变zuul.ribbonIsolationStrategy,Hystrix的线程隔离策略将用于所有路由。在这种情况下,HystrixThreadPoolKey被设置为默认的RibbonCommand。这意味着所有路由的HystrixCommands都在同一个Hystrix线程池中执行。这种行为可以通过以下配置来改变:
application.yml

zuul:
  threadPool:
    useSeparateThreadPools: true

The preceding example results in HystrixCommands being executed in the Hystrix thread pool for each route.

前面的示例导致HystrixCommands在Hystrix线程池中为每个路由执行。

In this case, the default HystrixThreadPoolKey is the same as the service ID for each route. To add a prefix to HystrixThreadPoolKey, set zuul.threadPool.threadPoolKeyPrefix to the value that you want to add, as shown in the following example:

在这种情况下,默认的HystrixThreadPoolKey与每个路由的服务ID相同。要向HystrixThreadPoolKey添加前缀,请设置zuul.threadpool.threadPoolKeyPrefix为您想添加的值,如下面的示例所示:

application.yml

zuul:
  threadPool:
    useSeparateThreadPools: true
    threadPoolKeyPrefix: zuulgw

7.11. 怎样提供a Key to Ribbon’s IRule

If you need to provide your own IRule implementation to handle a special routing requirement like a “canary” test, pass some information to the choose method of IRule.

如果您需要提供您自己的IRule实现来处理一个特殊的路由需求,如“canary”测试,传递一些信息给IRulechoose 方法。

com.netflix.loadbalancer.IRule.java

public interface IRule{
    public Server choose(Object key);
         :

You can provide some information that is used by your IRule implementation to choose a target server, as shown in the following example:

您可以提供您的IRule实现用来选择目标服务器的一些信息,如下面的示例所示:

RequestContext.getCurrentContext()
              .set(FilterConstants.LOAD_BALANCER_KEY, "canary-test");

If you put any object into the RequestContext with a key of FilterConstants.LOAD_BALANCER_KEY, it is passed to the choose method of the IRule implementation. The code shown in the preceding example must be executed before RibbonRoutingFilter is executed. Zuul’s pre filter is the best place to do that. You can access HTTP headers and query parameters through the RequestContext in pre filter, so it can be used to determine the LOAD_BALANCER_KEY that is passed to Ribbon. If you do not put any value with LOAD_BALANCER_KEY in RequestContext, null is passed as a parameter of the choose method.

如果您将任何对象放入带有key为FilterConstants.LOAD_BALANCER_KEYRequestContext中,它会被传递给IRule实现的choose方法。在执行RibbonRoutingFilter之前,必须执行前面示例中显示的代码。Zuul的前置过滤器就是最好的选择。您可以通过前置过滤器中的RequestContext访问HTTP头和查询参数,因此可以使用它来确定传递给Ribbon的LOAD_BALANCER_KEY。如果没有将LOAD_BALANCER_KEY中的任何值放到RequestContext中,则null将作为choose方法的参数传递。

8. 扩展配置: Archaius

Archaius is the Netflix client-side configuration library. It is the library used by all of the Netflix OSS components for configuration. Archaius is an extension of the Apache Commons Configuration project. It allows updates to configuration by either polling a source for changes or by letting a source push changes to the client. Archaius uses Dynamic< Type >Property classes as handles to properties, as shown in the following example:

Archaius是Netflix客户端配置库。它是所有Netflix OSS组件用于配置的库。Archaius是Apache Commons配置项目的扩展。它允许通过轮询源来进行更改,或者通过让源将更改推送到客户端来更新配置。Archaius使用Dynamic< Type >Property类作为属性的句柄,如下面的示例所示:

Archaius Example

class ArchaiusTest {
    DynamicStringProperty myprop = DynamicPropertyFactory
            .getInstance()
            .getStringProperty("my.prop");

    void doSomething() {
        OtherClass.someMethod(myprop.get());
    }
}

Archaius has its own set of configuration files and loading priorities. Spring applications should generally not use Archaius directly, but the need to configure the Netflix tools natively remains. Spring Cloud has a Spring Environment Bridge so that Archaius can read properties from the Spring Environment. This bridge allows Spring Boot projects to use the normal configuration toolchain while letting them configure the Netflix tools as documented (for the most part).

Archaius有自己的一组配置文件和加载优先级。Spring应用程序通常不应该直接使用Archaius,但是仍然需要在本地配置Netflix工具。Spring Cloud有一个Spring环境桥,以便Archaius可以从Spring环境读取属性。这个桥允许Spring Boot项目使用常规配置工具链,同时允许它们按照文档配置Netflix工具(大多数情况下)。

9. 路由和过滤器: Zuul

Routing is an integral part of a microservice architecture. For example, / may be mapped to your web application, /api/users is mapped to the user service and /api/shop is mapped to the shop service. Zuul is a JVM-based router and server-side load balancer from Netflix.

路由是微服务体系结构中不可分割的一部分。例如,/可以映射到您的web应用程序,/api/users映射到用户服务,/api/shop映射到商店服务。Zuul是Netflix的一款基于jvm的路由器和服务器端负载均衡器。

Netflix uses Zuul for the following:

  • Authentication

  • Insights

  • Stress Testing

  • Canary Testing

  • Dynamic Routing

  • Service Migration

  • Load Shedding

  • Security

  • Static Response handling

  • Active/Active traffic management

Zuul’s rule engine lets rules and filters be written in essentially any JVM language, with built-in support for Java and Groovy.

Zuul的规则引擎允许用任何JVM语言编写规则和过滤器,并内置了对Java和Groovy的支持。

The configuration property zuul.max.host.connections has been replaced by two new properties, zuul.host.maxTotalConnections and zuul.host.maxPerRouteConnections, which default to 200 and 20 respectively.

配置属性zuul.max.host.connections已被两个新属性 ,zuul.host.maxTotalConnectionszuul.host.maxPerRouteConnections替换,默认值分别为200和20。

The default Hystrix isolation pattern (ExecutionIsolationStrategy) for all routes is SEMAPHORE. zuul.ribbonIsolationStrategy can be changed to THREAD if that isolation pattern is preferred.

所有路由的默认Hystrix隔离模式(ExecutionIsolationStrategy)都是 SEMAPHOREzuul.ribbonIsolationStrategy如果是首选隔离模式,可以更改为THREAD

9.1.怎么引入zuul

To include Zuul in your project, use the starter with a group ID of org.springframework.cloud and a artifact ID of spring-cloud-starter-netflix-zuul. See the Spring Cloud Project page for details on setting up your build system with the current Spring Cloud Release Train.

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
    <version>2.2.4.RELEASE</version>
</dependency>

9.2.嵌入式 Zuul 反向代理

Spring Cloud has created an embedded Zuul proxy to ease the development of a common use case where a UI application wants to make proxy calls to one or more back end services. This feature is useful for a user interface to proxy to the back end services it requires, avoiding the need to manage CORS and authentication concerns independently for all the back ends.

Spring Cloud创建了一个嵌入式Zuul代理,以简化UI应用程序对一个或多个后端服务进行代理调用的通用用例的开发。这个特性对于将用户界面代理到它需要的后端服务非常有用,从而避免了为所有后端独立管理CORS和身份验证问题的需要。

To enable it, annotate a Spring Boot main class with @EnableZuulProxy. Doing so causes local calls to be forwarded to the appropriate service. By convention, a service with an ID of users receives requests from the proxy located at /users (with the prefix stripped). The proxy uses Ribbon to locate an instance to which to forward through discovery. All requests are executed in a hystrix command, so failures appear in Hystrix metrics. Once the circuit is open, the proxy does not try to contact the service.

要启用它,请使用’ @EnableZuulProxy ‘注释Spring Boot主类。这样做将导致本地调用被转发到适当的服务。按照约定,ID为’ users ‘的服务接收来自位于’ /users '(去掉前缀)的代理的请求。代理使用Ribbon定位要通过发现转发到的实例。所有请求都在hystrix命令中执行,因此在hystrix度量中会出现失败。一旦电路打开,代理就不会尝试与该服务联系。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值