1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > 【文档熟肉】spring cloud官方文档の中文熟肉之eureka

【文档熟肉】spring cloud官方文档の中文熟肉之eureka

时间:2020-11-28 12:29:33

相关推荐

【文档熟肉】spring cloud官方文档の中文熟肉之eureka

下面会陆续开始spring cloud中文文档的更新工作。

先更新个spring cloud最关键的eureka吧,原文地址:

https://docs.spring.io/spring-cloud-netflix/docs/current/reference/html/

Spring Cloud Netflix 3.0.2

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).

这个项目提供了Netflix OSS对spring boot应用的自动聚合和绑定spring环境其他spring编程模型。通过很少的注解你就可以快速的使你的应用中配置一个通用组件,并且构建一个带有经过Netflix测试过的组件的大型的分布式系统。这些组件包括了服务发现(eureka),服务熔断(hystrix),服务网关(zuul)和基于客户端的负载均衡(ribbon)。

1. Service Discovery: Eureka Clients

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服务发现提供者和客户端。提供者可以被配置和高可用部署,通过每个server向其他server复制登记了注册服务的state状态表(来实现数据的一致性)。

1.1. How to Include Eureka Client

怎样去实现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.

想要在你的项目中去实现一个eureka客户端,可以通过groupIDorg.springframework.cloud和articfactIDspring-cloud-starter-netflix-eureka-client来实现。可以通过此链接观看spring cloud项目介绍去具体的配置和构建你的系统。https://spring.io/projects/spring-cloud

1.2. Registering with Eureka

向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注册时,它会提供诸如自己的IP,端口,显示健康状况的URL,主页和其他细节。eureka接收从每个属于一个服务的注册实例的心跳信息。如果eureka没有及时接收心跳,实例会从注册表比正常 移除。

The following example shows a minimal Eureka client application:

下面的栗子展示了一个最简单的eureka客户端应用的配置:

@SpringBootApplication@RestControllerpublic 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到classpath,你的(eureka客户端)应用可以自动注册到eureka server。配置eureka server(应该是eureka客户端的配置才对),如下面示例展示:

application.ymleureka:client:serviceUrl:defaultZone: http://localhost:8761/eureka/

(上面一段配置表示client客户端向哪里发起注册申请,所以填的是server的defaultZone)

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是一个对任何没有配置此项的客户端默认配置的String类型的服务URL。(8761,eureka server的默认端口)

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

的defaultZone的snake-case 规范。

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).*

在classpath中包括spring-cloud-starter-netflix-eureka-client会使应用同时变成一个eureka实例(没错,它向它自己注册它自己)和eureka client(它可以通过查询注册表来定位其他服务)。这个实例的特征取决于eureka.instance.*配置项,但是如果你的应用的spring.application.name有值的话,默认也是可以的。(它(eureka server的应用名称)是eureka默认的服务id或者说VIP(虚拟ip))

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

可以通过观看EurekaInstanceConfigBeanEurekaClientConfigBean来获取更多的配置细节。

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.enabled为false。eureka客户端也可以被禁用,通过设置spring.cloud.discovery.enabled为false。

1.3. Authenticating with the Eureka Server

使用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.defaultZone这个URL已经嵌入的话,那么http基本身份认证就已经被添加到了你的eureka客户端了。(格式如下:

user:password@localhost:8761/eureka)。对于更多复杂的需求,你可以创造一个DiscoveryClientOptionalArgs类型的bean并且注入到ClientFilter实例中,他们都会用在从客户端到服务端的请求里。

When Eureka server requires client side certificate for authentication, the client side certificate and trust store can be configured via properties, as shown in following example:

当eureka服务端需要客户端隐藏(身份认证)证书时,客户端就会隐藏(身份认证)证书并且可以通过属性配置信任仓库,如下面栗子所示:

application.yml

eureka:client:tls:enabled: truekey-store: <path-of-key-store>key-store-type: PKCS12key-store-password: <key-store-password>key-password: <key-password>trust-store: <path-of-trust-store>trust-store-type: PKCS12trust-store-password: <trust-store-password>

The eureka.client.tls.enabled needs to be true to enable Eureka client side TLS. When eureka.client.tls.trust-store is omitted, a JVM default trust store is used. The default value for eureka.client.tls.key-store-type and eureka.client.tls.trust-store-type is PKCS12. When password properties are omitted, empty password is assumed.

允许eureka客户端隐藏TLS需要eureka.client.tls.enabled设置为true。当省略eureka.client.tls.trust-store时,会使用JVM默认的信任仓库。eureka客户端的eureka.client.tls.key-store-typeeureka.client.tls.trust-store-type的默认值为PKCS12。当密码属性被忽略时,密码默认为空密码。

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的限制,无法支持(去)每一个eureka服务端进行基础身份认证,因此仅支持验证(某一个eureka服务端的)第一组凭据。

If you want to customize the RestTemplate used by the Eureka HTTP Client you may want to create a bean of EurekaClientHttpRequestFactorySupplier and provide your own logic for generating a ClientHttpRequestFactory instance.

如果你想要通过eureka HTTP客户端定制一个RestTemplate,你可以通过创造一个EurekaClientHttpRequestFactorySupplier的bean并且通过提供一个ClientHttpRequestFactory实例来实现你自己的逻辑。

**

1.4. Status Page and Health Indicator

**

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}/infohealthCheckUrlPath: ${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 (spring cloud的一个版本)中它也会被允许设置状态和健康街检查的URL。在Edgware(spring cloud的一个版本)中已经删除了此要求。

1.5. Registering a Secure Application

安全的注册一个应用

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

如果你的APP想要通过HTTPS去连接(eureka) ,你可以在EurekaInstanceConfigBean中设置两个属性

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服务发现客户端一定会返回一个经过这种方式配置过用于通过HTTPS连接service的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}/infohealthCheckUrl: https://${eureka.hostname}/healthhomePageUrl: 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终止在代理中(例如,如果你运行在云端或者其他平台作为一个服务(平台即服务,PaaS)),那么你需要确定你的代理的forwarded请求头被你的应用拦截和处理。如果嵌入了spring boot应用的Tomcat容器对于“X-Forwarded-\*”有精确的配置,它会自动进行处理。应用程序提供的指向自身的链接错误(错误的主机,端口或协议)表明此配置错误。

1.6. Eureka’s Health Checks

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使用客户端的心跳去判断一个客户端是否在线。除非另有说明,根据spring boot的Actuator,服务发现客户端并不会(向eureka服务端)传播现在的客户端健康检查状态。最后,在成功的注册后,eureka总是会将应用状态展示为UP(也就是默认的话,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中注册为UNKNOWN状态。

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

如果你需要更多的健康检查的控制,可以考虑实现你自己的flix.appinfo.HealthCheckHandler

1.7. Eureka Metadata for Instances and Clients

eureka实例和客户端的元数据(猜测eureka实例指的是服务端,因为真正的注册中心就是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元数据是如何工作的是值得的,所以你可以在自己的平台上以合理的方式去使用它。标准的元数据信息如hostname,ip address, 端口数量,状态页,健康检查。这些在服务注册时发布出来并且被客户端用于以直接连接的方式连接服务。可以在实例注册时在eureka.instance.metadataMap中添加附加的元数据,并且这个元数据对于远程的客户端是可见的。通常来说,附加的元数据不会改变客户端的行为,除非让客户端知道元数据的意义。这里有一对特殊的栗子,稍后在文档里会有描述,spring cloud已经对metadata map指定了含义。

1.7.1. Using Eureka on Cloud Foundry

在Cloud Foundry使用eureka

(注,Cloud Foundry是一种平台即服务(PaaS),兼容多种基础设施云,提供多种开发框架和应用服务)

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有一个全局路由器所以所有同名的实例都有一个相同的hostname(其他具有类似架构的PAAS解决方案具有相同的措施)。这对于使用eureka来说并不是关键的障碍。可是,如果你想要路由(推荐甚至是强制性的,这取决于你的平台如何设置),你需要精准的设置hostname和端口数量(区分安全的和不安全的),然后才能进行路由。你可能也想要使用实例元数据,这样你可以识别客户端的元数据(比如,自定义负载均衡)。默认的,eureka.instance.instanceIdvcap.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实例行如何设置取决于上述的栗子,你可能可以去注册和使用虚拟机的ip地址进行服务对服务的直接调用。这种特性在关键网络服务(PWS)上还没有实现。

1.7.2. Using Eureka on AWS

在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 bean = new EurekaInstanceConfigBean(inetUtils);AmazonInfo info = AmazonInfo.Builder.newBuilder().autoBuild("eureka");bean.setDataCenterInfo(info);return bean;}

1.7.3. Changing the Eureka Instance 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实例在注册时会带有一个和它的host名字一样的id(这就意味着,每个host仅可以有一个服务)。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是自动填进去的,所以不需要(人为的设置)随机值。

1.8. Using the EurekaClient

使用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 flix.discovery.EurekaClient (as opposed to the Spring Cloud DiscoveryClient), as shown in the following example:

一旦你的应用是一个服务发现客户端,你可以使用它从eureka服务端去发现服务实例。一种可以这么做的方式是使用本地的 flix.discovery.EurekaClient(而不是spring cloud的DiscoveryClient),如下所示:

@Autowiredprivate 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(或者在任何应用上下文可能无法启动的地方)标注的方法中使用EurekaClient 。它在SmartLifecycle 中初始化(phase=0),因此,你最早可以依靠它的可用性是在另一个具有较高阶段的SmartLifecycle中(使用EurekaClient )。

1.8.1. EurekaClient without Jersey

By default, EurekaClient uses Spring’s RestTemplate for HTTP communication. If you wish to use Jersey instead, you need to add the Jersey dependencies to your classpath. The following example shows the dependencies you need to add:

默认的,EurekaClient 使用spring的RestTemplate 进行http通信。如果你希望使用Jersey 代替,你需要在你的classpath里添加Jersey 的依赖。下面的栗子展示了你需要添加的依赖:

<dependency><groupId>com.sun.jersey</groupId><artifactId>jersey-client</artifactId></dependency><dependency><groupId>com.sun.jersey</groupId><artifactId>jersey-core</artifactId></dependency><dependency><groupId>com.sun.jersey.contribs</groupId><artifactId>jersey-apache-client4</artifactId></dependency>

1.9. Alternatives to the Native Netflix EurekaClient

本地Netflix EurekaClient的替代产品

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 .ribbon.listOfServers to a comma-separated list of physical addresses (or hostnames), where is the ID of the client.

你不需要使用 Netflix 原始的 EurekaClient。同样的,在某些种类的wrapper后使用它会更加方便。spring cloud对feign有提供支持(一个REST客户端builder),并且spring 的RestTemplate 通过逻辑上的eureka服务鉴定器(VIP)取代了物理上的URL。通过一个物理机的列表去配置ribbon,你可设置<client>.ribbon.listOfServers为逗号分隔的物理地址(或主机名)列表,为客户端的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.DiscoveryClient,它提供了针对服务发现客户端的简单的API(),如下面栗子所示:

@Autowiredprivate 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. Why Is It so Slow to Register a Service?

为什么注册一个服务这么慢

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它自己的服务在哪个zone(空间)里。你可以通过使用metadataMap 属性这么做(以达到目的)。例如,如果服务1已经部署在了空间1和空间2,你需要去服务1中设置下面的eureka属性:

Service 1 in Zone 1

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

Service 1 in Zone 2

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

1.12. Refreshing Eureka Clients

刷新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.

默认的,eureka客户端的bean是可刷新的,意味着eureka客户端的属性可以(在运行期间)被改变和刷新。当刷新客户端发生时将会无法在eureka服务端注册,所有提供服务的实例在短时间内将不可用。一个排除这种状况的方法是禁止eureka客户端的刷新。这么做的话,可以去设置eureka.client.refresh.enable=false

1.13. Using Eureka with Spring Cloud LoadBalancer

通过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的 Cloud LoadBalancer ZonePreferenceServiceInstanceListSupplier提供支持。来自eureka实例的元数据的zone值用于设置spring-clod-loadbalancer-zone属性的值,它用于通过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,它可以使用服务的hostname的实体名称作为zone的代理。

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).

如果zone数据没有其他来源,那么可以推测,基于客户端配置(而不是实例配置),我们使用eureka.client.availabilityZones,一个从region name到一系列zone的映射,并且拿出所有实例自己的region对应的第一个zone(eureka.client.region,默认是us-east-1,为了向原始的Netflix(版本)做兼容)

2. Service Discovery: Eureka Server

服务发现:eureka服务端

This section describes how to set up a Eureka server.

这部分将描述如何去设置一个eureka服务端。

2.1. How to Include Eureka Server

怎样实eureka服务端

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.

想要在你的项目中实现eureka服务端,可以使用group idorg.springframework.cloud和artifact idspring-cloud-starter-netflix-eureka-server。为了配置现在spring cloud发行版到你的系统,可以去spring cloud项目主页查看细节。

2.2. How to Run a Eureka Server

怎样运行一个eureka服务端

The following example shows a minimal Eureka server:

下面的栗子展示了最简单的eureka服务端:

@SpringBootApplication@EnableEurekaServerpublic 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/*.

服务端有一个带有UI界面和在“ /eureka/”*下的HTTP API功能的endpoint的主页。

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

下面的链接有一些eureka背景以供阅读: flux capacitor和google group discussion。

Due to Gradle’s dependency resolution rules and the lack of a parent bom feature, depending on spring-cloud-starter-netflix-eureka-server can cause failures on application startup. To remedy this issue, add the Spring Boot Gradle plugin and import the Spring cloud starter parent bom as follows:

由于Gradle(版本)的依赖规则和父bom功能的缺失,依赖于spring-cloud-starter-netflix-eureka-server可能导致应用启动失败。为了补救这个问题,(可以)添加Spring Boot Gradle plugin 插件和引入Spring cloud starter 父bom如下:

buildscript {dependencies {classpath("org.springframework.boot:spring-boot-gradle-plugin:{spring-boot-docs-version}")}}apply plugin: "spring-boot"dependencyManagement {imports {mavenBom "org.springframework.cloud:spring-cloud-dependencies:{spring-cloud-version}"}}

2.3. High Availability, Zones and Regions

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客户端并且需要(至少一个)service 的URL去寻找它。如果你不提供这个(URL),服务(依然可以)运行和工作,但是它会在你的日志里充满了无法注册其他同伴()的警告。

See also below for details of Ribbon support on the client side for Zones and Regions.

观看下面ribbon对客户端一侧的zones和regions提供的支持细节:

2.4. Standalone Mode

独立模式

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)。在标准模式中,你可能更倾向于选择关掉客户端侧的这种行为,使它停止不断尝试连接其他(可能指eureka服务端)并且失败。下面的栗子展示了怎样去关掉客户端一侧的这种行为:

application.yml (Standalone Eureka Server)

server:port: 8761eureka:instance:hostname: localhostclient:registerWithEureka: falsefetchRegistry: falseserviceUrl:defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/

Notice that the serviceUrl is pointing to the same host as the local instance.

注意serviceUrl指向了和本地实例一样的host

2.5. Peer Awareness

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可以更加有弹性,并且被多个运行的实例访问注册。事实上,这是一种默认(开启)的行为,所以所有你需要做的是向每个(eureka服务端)添加一个有效serviceUrl ,如下面的栗子所示:

application.yml (Two Peer Aware Eureka Servers)

spring:profiles: peer1eureka:instance:hostname: peer1client:serviceUrl:defaultZone: https://peer2/eureka/---spring:profiles: peer2eureka:instance:hostname: peer2client: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 .InetAddress).

在上面的栗子中,我们有一个yaml文件可以通过在不同的spring文件上运行,去在两个host上去跑同一个(eureka)服务。你可以通过这种配置方式,在同一个主机的相同端口,通过多个 /etc/hosts来命名host名称,来测试这种感知能力(生产环境没什么用)。事实上,在eureka实例中,如果你在运行一台机器时是不需要你了解它的host名称的(在默认情况下,和使用.InetAddress类似)

2.6. When to 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地址而不是host名称要更好一些。当设置eureka.instance.preferIpAddresstrue,并且应用向eureka发起注册时,使用ip地址而不是host名称要更好一些。

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. Securing The 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/** 端点禁用此要求。 例如:

@EnableWebSecurityclass WebSecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.csrf().ignoringAntMatchers("/eureka/**");super.configure(http);}}

For more information on CSRF see the Spring Security documentation.

有关 CSRF 的更多信息,请参阅 Spring Security 文档。

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

可以在 Spring Cloud Samples repo 中找到演示 Eureka Server。

2.8. JDK 11 Support

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. Configuration properties

To see the list of all Spring Cloud Netflix related configuration properties please check the Appendix page.

要查看所有 Spring Cloud Netflix 相关配置属性的列表,请查看附录页面。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。