Spring Cloud 详解(第一篇:Eureka注册中心)

Spring Cloud 详解(第一篇:Eureka注册中心)

@(微服务)[java|spring-cloud|eureka]

Eureka 注册中心是入门Spring Cloud微服务架构的必学组件,是学习所有其他组件的基础和基石。

微服务的核心思想是分而治之,各司其职,而如何将这些各司其职的微服务实例协同起来,则需服务注册中心的介入。在Spring Cloud微服务体系中,这个第三方协作者的角色由Eureka完成。


1、搭建Eureka服务端

搭建一个简单的Eureka服务端十分容易(搭建高可用的注册中心也不难,Eureka直接支持)。
- 第一步:添加Mavan依赖 :加入Spring Boot和Spring Cloud相关依赖,并对应好版本;
- 第二步:注解启用类 :在启用类上加入@EnableEurekaServer注解;
- 第三步:配置application.yml文件 :修改默认配置,适应生产环境。

第一步:添加Mavan依赖

基本的pom.xml配置信息如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.siemens.springcloud</groupId>
    <artifactId>eureka-server</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>eureka-server</name>
    <description>Demo project for Spring Boot</description>

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

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <spring-cloud.version>Dalston.SR4</spring-cloud.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka-server</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

由于历史原因(相信生产环境中使用的Spring Boot大多在1.3-1.5之间),Spring-Boot选用了1.5.8的版本,对应的的Spring-Cloud版本为Dalston.SR4。

第二步:注解启用类
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {

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

}
第三步:配置application.yml文件
server:
  port: 8761

eureka:
  instance:
    hostname: localhost
  server:
    enable-self-preservation: false      # 关闭自我保护模式(默认为打开)
    eviction-interval-timer-in-ms: 5000  # 续期时间,即扫描失效服务的间隔时间(缺省为60*1000ms)
  client:
    register-with-eureka: false
    fetch-registry: false
    service-url:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/

1、eureka.client.register-with-eureka: 对于同一个进程,既可以作为注册中心的服务端,也可以作为注册中心的客户端,在本例中,注册中心提供单一的注册服务功能,不提供其他接口服务能力,所以设置为false,最终不作为服务实例注册在注册中心中供其他服务调用。
2、eureka.server.enable-self-preservation:
是否开启自我保护模式,默认为true。

默认情况下,如果Eureka Server在一定时间内没有接收到某个微服务实例的心跳,Eureka Server将会注销该实例(默认90秒)。但是当网络分区故障发生时,微服务与Eureka Server之间无法正常通信,以上行为可能变得非常危险了——因为微服务本身其实是健康的,此时本不应该注销这个微服务。

Eureka通过“自我保护模式”来解决这个问题——当Eureka Server节点在短时间内丢失过多客户端时(可能发生了网络分区故障),那么这个节点就会进入自我保护模式。一旦进入该模式,Eureka Server就会保护服务注册表中的信息,不再删除服务注册表中的数据(也就是不会注销任何微服务)。当网络故障恢复后,该Eureka Server节点会自动退出自我保护模式。

综上,自我保护模式是一种应对网络异常的安全保护措施。它的架构哲学是宁可同时保留所有微服务(健康的微服务和不健康的微服务都会保留),也不盲目注销任何健康的微服务。使用自我保护模式,可以让Eureka集群更加的健壮、稳定。

当我们在本地调试基于Eureka的程序时,基本上都会碰到这样一个问题,在服务注册中心的信息面板中出现类似的红色警告信息:

EMERGENCY! EUREKA MAY BE INCORRECTLY CLAIMING INSTANCES ARE UP WHEN THEY’RE NOT. RENEWALS ARE LESSER THAN THRESHOLD AND HENCE THE INSTANCES ARE NOT BEING EXPIRED JUST TO BE SAFE.

实际上,该警告就是触发了Eureka Server的自我保护机制。之前我们介绍过,服务注册到Eureka Server之后,会维护一个心跳连接,告诉Eureka Server自己还活着。Eureka Server在运行期间,会统计心跳失败的比例在15分钟之内是否低于85%,如果出现低于的情况(在单机调试的时候很容易满足,实际在生产环境中通常是网络不稳定导致),Eureka Server会将当前的实例注册信息保护起来,让这些实例不会过期,尽可能的保护这些注册信息。在这段保护 期间内实例出现问题,那么客户端很容易拿到实际已经不存在的服务实例,会出现调用失败的情况,所以客户端必须要有容错机制,比如可以使用请求重试、断路器等机制。
由于本地调试很容易触发注册中心的保护机制,这会使得注册中心维护的服务实例不那么准确。所以,我们在本地进行开发的时候,可以使eureka.server.enable-self-preservation=false参数关闭保护机制,以确保注册中心可以将不可用的实例正确剔除。

3、eureka.server.eviction-interval-timer-in-ms:
eureka server清理无效节点的时间间隔,默认60000毫秒,即60秒。服务下线存在两种情况,一种是客户端主要发送“服务下线”的请求,另外一种是通过定时任务扫描,每隔固定的时间清理无效的节点信息。清理无效节点的策略由客户端决定,客户端节点会设置相应的上报时间和最大超时时间(最大超时时间必须超过上报时间,推介设置为3倍关系),eureka server至上一次收到client的心跳之后,等待下一次心跳的超时时间,在这个时间内若没收到下一次心跳,则将移除该instance。

到此为止,启动Spring Boot程序,访问http://localhost:8761/即可访问到如下web界面:

这里写图片描述

如图所示,注册中心已正常启动,并关闭了保护模式,且当前尚无实例注册到该Eureka Server。

2、搭建Eureka客户端

成功搭建Eureka Server后,接着我们就可以将服务实例注册到该服务中心了,具体步骤如下:
- 第一步:添加Mavan依赖 :加入Spring Boot和Spring Cloud相关依赖,并对应好版本;
- 第二步:注解启用类 :在启用类上加入@EnableEurekaClient注解;
- 第三步:配置application.yml文件 :修改默认配置,适应生产环境。

第一步:添加Mavan依赖

Eureka 客户端的maven配置和服务器端配置基本相同,唯一不同的地方在于客户端需要设置健康状态信息,需要引入spring-boot-starter-actuator依赖,如下所示:

<dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
第二步:注解启用类

在启用类上加入@EnableEurekaClient注解即可,通过该注解,项目下所有被@RestController注解的对外服务接口将可通过注册-发布的方式对外提供服务。

第三步:配置application.yml文件
server:
  port: 8762
spring:
  application:
    name: service-hi
  #zipkin:
    #base-url: http://localhost:9411

eureka:
  instance:
    lease-renewal-interval-in-seconds: 5      # 心跳时间,即服务续约间隔时间(缺省为30s)
    lease-expiration-duration-in-seconds: 15  # 发呆时间,即服务续约到期时间(缺省为90s)
  client:
    registry-fetch-interval-seconds: 10 # 拉取服务注册信息间隔(缺省为30s)
    service-url:
      defaultZone: http://localhost:8761/eureka/
    healthcheck:
      enabled: true # 开启健康检查(依赖spring-boot-starter-actuator)

1、eureka.instance.lease-renewal-interval-in-seconds:
lease-renewal-interval-in-seconds,表示eureka client发送心跳给server端的频率。如果在leaseExpirationDurationInSeconds后,server端没有收到client的心跳,则将摘除该instance。除此之外,如果该instance实现了HealthCheckCallback,并决定让自己unavailable的话,则该instance也不会接收到流量,默认30秒。

2、eureka.instance.lease-expiration-duration-in-seconds:
lease-expiration-duration-in-seconds,表示eureka server至上一次收到client的心跳之后,等待下一次心跳的超时时间,在这个时间内若没收到下一次心跳,则将移除该instance,该值默认为90秒。

3、eureka.client.registry-fetch-interval-seconds:
表示eureka client间隔多久去拉取服务注册信息,默认为30秒,对于api-gateway,如果要迅速获取服务注册状态,可以缩小该值,比如5秒。

配置结束之后,启动Spring-Boot程序,可以发现原来的注册界面多了一个注册的实例,则注册成功:
这里写图片描述

  • 6
    点赞
  • 34
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Spring Cloud Eureka 是一款服务注册和发现的组件,它可以让开发人员更方便地创建分布式系统。下面是 Spring Cloud Eureka 配置的详细解释: 1. 引入依赖 在项目的 pom.xml 文件中,需要添加以下依赖: ``` <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId> <version>2.2.3.RELEASE</version> </dependency> ``` 2. 配置文件 在配置文件中需要添加以下内容: ``` spring: application: name: eureka-server server: port: 8761 eureka: instance: hostname: localhost client: register-with-eureka: false fetch-registry: false service-url: defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/ ``` 这里定义了服务的名称和端口,以及 Eureka Server 的配置。其中,`register-with-eureka` 和 `fetch-registry` 的值都设置为 false,表示该服务既不需要注册到 Eureka 服务器上,也不需要从 Eureka 服务器上获取服务注册表信息。 3. 启动 Eureka Server 在 Spring Boot 应用程序中添加 `@EnableEurekaServer` 注解即可启动 Eureka Server。例如: ``` @SpringBootApplication @EnableEurekaServer public class EurekaServerApplication { public static void main(String[] args) { SpringApplication.run(EurekaServerApplication.class, args); } } ``` 4. 注册服务 在需要注册到 Eureka 服务器上的服务中,需要添加以下依赖: ``` <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> <version>2.2.3.RELEASE</version> </dependency> ``` 在服务的配置文件中添加以下内容: ``` spring: application: name: service-hello eureka: client: service-url: defaultZone: http://localhost:8761/eureka/ ``` 其中,`application.name` 的值为服务的名称,`eureka.client.service-url.defaultZone` 的值为 Eureka Server 的地址。 5. 启动服务 在服务的主类中添加 `@EnableDiscoveryClient` 注解,表示该服务需要注册到 Eureka 服务器上。例如: ``` @SpringBootApplication @EnableDiscoveryClient public class ServiceHelloApplication { public static void main(String[] args) { SpringApplication.run(ServiceHelloApplication.class, args); } } ``` 通过以上步骤,就可以使用 Spring Cloud Eureka 实现服务注册和发现了。 ### 回答2: SpringCloud EurekaSpringCloud的核心组件之一,它提供了一种服务治理的解决方案。在分布式系统中,服务之间的相互调用是不可避免的,Eureka可以管理服务之间的依赖关系,确保服务间的通信和服务的高可用性。本文将介绍SpringCloud Eureka的配置详解。 一、Eureka Server配置 1. 引入Eureka Server依赖 ```xml <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka-server</artifactId> </dependency> ``` 2. 配置application.yml ```yaml server: port: 8761 spring: application: name: eureka-server profiles: active: dev eureka: instance: hostname: localhost client: serviceUrl: defaultZone: http://localhost:8761/eureka/ server: enable-self-preservation: false eviction-interval-timer-in-ms: 30000 response-cache-update-interval-ms: 30000 registry-fetch-interval-seconds: 5 prefer-same-zone-eureka: true ``` 注释: 1. serviceUrl.defaultZone 是 Eureka Server 上的服务 URL,这里是设置为本地的 URL。 2. server.enable-self-preservation 为是否开启自我保护模式,开启后会自动将当前实例加入到Eureka Server的服务列表中。 3. eviction-interval-timer-in-ms:清理失效节点的时间间隔,默认为 60 秒。 4. registry-fetch-interval-seconds:Eureka Server 获取注册表数据的间隔时间,默认为 30 秒。 5. prefer-same-zone-eureka:是否优先选择同一个 Zone 的实例。 二、Eureka Client配置 1. 引入Eureka Client依赖 ```xml <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka</artifactId> </dependency> ``` 2. 配置application.yml ```yaml server: port: 8080 spring: application: name: service-one profiles: active: dev eureka: instance: instance-id: ${spring.application.name}:${random.int} prefer-ip-address: true # 避免hostname无法访问 client: serviceUrl: defaultZone: http://localhost:8761/eureka/ fetch-registry: true register-with-eureka: true healthcheck: enabled: true server: wait-time-in-ms-when-sync-empty: 0 ``` 注释: 1. instance.instance-id:实例的名称,建议加上随机数,避免实例名冲突。 2. client.fetch-registry:是否从 Eureka Server 获取注册表。 3. client.register-with-eureka:是否将服务注册到 Eureka Server。 4. healthcheck.enabled:是否开启健康检查,开启后Eureka Server能够监测到服务是否存活。 5. 实际开发中常用的还有其他的配置参数,例如eureka.instance.ip-address,eureka.instance.non-secure-port等。 三、实现服务注册 1. 实现服务接口 ```java @Service public class UserServiceImpl implements IUserService { @Override public User getUserById(int id) { return new User(id, "Tom"); } } ``` 2. 添加@EnableDiscoveryClient注解 ```java @EnableDiscoveryClient @SpringBootApplication public class ServiceOneApplication { public static void main(String[] args) { SpringApplication.run(ServiceOneApplication.class, args); } } ``` 3. 在Controller中使用RestTemplate调用其他服务 ```java @RestController public class UserController { @Autowired private RestTemplate restTemplate; @GetMapping("/user/{id}") public User getUserById(@PathVariable int id) { String url = "http://service-two/user/" + id; return restTemplate.getForObject(url, User.class); } } ``` 四、小结 本文简要介绍了 SpringCloud Eureka 的基本配置,包括Eureka Server和Eureka Client的配置,以及服务注册的实现。在实际开发中,我们根据具体需要进行更加详细的配置和实现。SpringCloud Eureka作为SpringCloud微服务体系的核心组件之一,是服务治理的不二选择。 ### 回答3: Spring Cloud Eureka是一个开源的服务注册中心,用来解决微服务系统中服务的注册与发现问题。在微服务架构中,由于服务数量庞大,需要有一个中心化的服务注册与发现机制来协调各个服务之间的调用关系。Spring Cloud Eureka就是这样一个核心组件,它可以帮助我们管理和调度微服务。下面,我们就来详细了解一下Spring Cloud Eureka的配置。 在Spring Boot中,我们可以使用@EnableEurekaServer注解来启用Eureka Server。具体配置如下: ```java @SpringBootApplication @EnableEurekaServer public class EurekaApplication { public static void main(String[] args) { SpringApplication.run(EurekaApplication.class, args); } } ``` @EnableEurekaServer注解用来启用Eureka Server功能。Spring Boot应用启动后,Eureka Server也会自动启动。默认情况下,Eureka Server的端口号为8761。 接下来,我们需要在application.yml配置文件中添加如下配置: ```yaml server: port: 8761 # 指定Eureka Server的端口号 eureka: instance: hostname: localhost # Eureka Server的主机名,默认为localhost client: register-with-eureka: false # 是否向Eureka Server注册自己,默认为true fetch-registry: false # 是否检索服务列表,默认为true service-url: defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/ ``` 在配置文件中,我们可以指定Eureka Server的端口号、主机名、服务注册与检索等参数。其中,register-with-eureka参数表示是否向Eureka Server注册自己,默认为true,如果我们不想在Eureka Server上注册自己,可以将该参数设置为false。fetch-registry参数表示是否检索服务列表,默认为true,如果我们不想从Eureka Server上检索服务列表,可以将该参数设置为false。service-url参数是Eureka Server的服务地址,可以指定多个服务地址,以逗号分隔。 在服务提供者中,我们也需要添加Eureka Client依赖,并进行相关配置。在build.gradle文件中添加如下依赖: ```gradle dependencies { implementation 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-client' } ``` 在application.yml配置文件中添加如下配置: ```yaml eureka: client: service-url: defaultZone: http://localhost:8761/eureka/ # 指定Eureka Server的服务地址 spring: application: name: service-hello # 服务名称,必须唯一 ``` 在服务启动时,会通过Eureka Client向Eureka Server注册自己,并提供服务。service-hello就是服务的名称,必须唯一。在客户端中,我们只需要使用服务名称来调用服务,Eureka Client会帮我们负责服务的发现和负载均衡。 以上就是Spring Cloud Eureka的基本配置。通过对Eureka Server和Eureka Client的配置,我们可以实现服务的注册、发现和负载均衡功能。在实际应用中,服务治理是微服务架构中不可或缺的一部分,Spring Cloud Eureka为我们提供了很好的解决方案。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值