Eureka 服务注册中心 😶

什么是服务治理:

SpringCloud 封装了 Netflix 公司开发的 Eureka 模块来实现服务治理

在传统的 rpc 远程调用框架中,管理每个服务与服务之间依赖关系比较复杂,管理比较复杂,所以需要使用服务治理,管理服务于服务之间依赖关系,可以实现服务调用、负载均衡、容错等,实现服务发现与注册。

什么是服务注册与发现

Eureka 采用了 CS 的设计结构,Eureka Server 服务注册功能的服务器,它是服务注册中心。而系统中的其他微服务,使用 Eureka 的客户端连接到 Eureka Server 并维持心跳连接。这样系统的维护人员就可以通过 Eureka Server 来监控系统中各个微服务是否正常运行。这点和 zookeeper 很相似

在服务注册与发现中,有一个注册中心。当服务器启动时候,会把当前自己服务器的信息 比如服务地址 通讯地址等以别名方式注册到注册中心上。另一方(消费者服务提供者),以该别名的方式去注册中心上获取到实际的服务通讯地址,然后再实现本地 RPC 调用。RPC 远程调用框架核心设计思想:在于注册中心,因为便用注册中心管理每个服务与服务之间的一个依赖关系(服务治理概念)。在任何 rpc 远程框架中,都会有一个注册中心(存放服务地址相关信息(接口地址))

Eureka 包含两个组件:Eureka Server 和 Eureka Client

Eureka 官方停更不停用,以后可能用的越来越少。

Eureka 是 Netflix 开发的,一个基于 REST 服务的,服务注册与发现的组件,以实现中间层服务器的负载平衡和故障转移。

Eureka 分为 Eureka Server 和 Eureka Client 及服务端和客户端。

Eureka Server 为注册中心,是服务端,而服务提供者和消费者即为客户端,消费者也可以是服务者,服务者也可以是消费者。同时 Eureka Server 在启动时默认会注册自己,成为一个服务,所以 Eureka Server 也是一个客户端,这是搭建 Eureka 集群的基础。

Eureka Client:一个 Java 客户端,用于简化与 Eureka Server 的交互(通常就是微服务中的客户端和服务端)。通过注册中心进行访问。是一个 Java 客户端,用于简化 Eureka Server 的交互,客户端同时也具备一个内置的、使用轮询(roundrobin)负载算法的负载均衡器在应用启动后,将会向 Eureka Server 发送心跳(默认周期为 30 秒)。如果 Eureka Server 在多个心跳周期内没有接收到某个节点的心跳,Eureka Server 将会从服务注册表中把这个服务节点移除(默认 90 秒)

Eureka Server:提供服务注册服务,各个微服务节,通过配置启动后,会在 Eureka Serverc 中进行注册,这样 Eureka Server 中的服务注册表中将会存储所有可用服务节点信息,服务节点的信息可以在界面中直观看到。
服务在 Eureka 上注册,然后每隔 30 秒发送心跳来更新它们的租约。如果客户端不能多次续订租约,那么它将在大约 90 秒内从服务器注册表中剔除。注册信息和更新被复制到集群中的所有 eureka 节点。来自任何区域的客户端都可以查找注册表信息(每 30 秒发生一次)来定位它们的服务(可能在任何区域)并进行远程调用

服务提供者向注册中心注册服务,并每隔 30 秒发送一次心跳,就如同人还活着存在的信号一样,如果 Eureka 在 90 秒后还未收到服务提供者发来的心跳时,那么它就会认定该服务已经死亡就会注销这个服务。这里注销并不是立即注销,而是会在 60 秒以后对在这个之间段内“死亡”的服务集中注销,如果立即注销,势必会对 Eureka 造成极大的负担。这些时间参数都可以人为配置。

Eureka 还有自我保护机制,如果在 15 分钟内超过 85%的节点都没有正常的心跳,那么 Eureka 就认为客户端与注册中心出现了网络故障,所以不会再接收心跳,也不会删除服务。

客户端消费者会向注册中心拉取服务列表,因为一个服务器的承载量是有限的,所以同一个服务会部署在多个服务器上,每个服务器上的服务都会去注册中心注册服务,他们会有相同的服务名称但有不同的实例 id,所以拉取的是服务列表。我们最终通过负载均衡来获取一个服务,这样可以均衡各个服务器上的服务。

1、单机 Eureka 构建步骤

消费者端口 80,提供者端口 8001,Eureka 端口 7001

1、创建单机 Eureka 模块 cloud-eureka-server7001

2、编写 pom

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<?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">
<parent>
<artifactId>springCloud2023</artifactId>
<groupId>com.jcvv.springcloud</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>

<artifactId>cloud-eureka-server7001</artifactId>

<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<!-- 引入自己定义的api通用包,可以使用Payment支持Entity-->
<dependency>
<groupId>com.jcvv.springcloud</groupId>
<artifactId>cloud-api-common</artifactId>
<version>${project.version}</version>
</dependency>
<!--eureka-server-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

</dependencies>

</project>

3、编写 application.yml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
server:
port: 7001

eureka:
instance:
hostname: localhost # eureka 服务端的实例名称

client:
# false 代表不向服务注册中心注册自己,因为它本身就是服务中心
register-with-eureka: false
# false 代表自己就是服务注册中心,自己的作用就是维护服务实例,并不需要去检索服务
fetch-registry: false
service-url:
# 设置与 Eureka Server 交互的地址,查询服务 和 注册服务都依赖这个地址 http://localhost:7001/eureka/
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/

4、编写主启动类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package com.jcvv.springcloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

/**
* @Classname EurekaMain7001
* @Description chengzhi
* @Created by chengzhi
*/
@SpringBootApplication
@EnableEurekaServer//注册中心
public class EurekaMain7001 {
public static void main(String[] args) {
SpringApplication.run(EurekaMain7001.class,args);
}
}

5、运行 localhost:7001,验证是否成功

1-1、8001 注册进 Eureka 成为提供者

  • 改 pom 添加依赖

    1
    2
    3
    4
    5
    6
    <!--eureka-client-->
    <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>

  • 写 YML

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    eureka:
    client:
    # 注册进 Eureka 的服务中心
    register-with-eureka: true
    # 检索服务中心的其它服务
    # 单节点无所谓,集群必须设置为true才能配合ribbon使用负载均衡
    fetch-registry: true
    service-url:
    # 设置与 Eureka Server 交互的地址
    defaultZone: http://localhost:7001/eureka/
  • 改主启动类

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    package com.jcvv.springcloud;

    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

    /**
    * @Classname PaymentMain8001
    * @Description chengzhi
    * @Created by chengzhi
    */
    @SpringBootApplication
    @EnableEurekaClient
    public class PaymentMain8001 {
    public static void main(String[] args) {
    SpringApplication.run(PaymentMain8001.class, args);
    }
    }

  • 测试

1-2、80 注册进 Eureka 成为消费者

  • 改 pom 文件 导入依赖

    1
    2
    3
    4
    5
    <!--eureka-client-->
    <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>
  • 写 YML

    1
    2
    3
    4
    5
    6
    eureka:
    client:
    register-with-eureka: true
    fetch-registry: true
    service-url:
    defaultZone: http://localhost:7001/eureka/
  • 编写主启动类

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    package com.jcvv.springcloud;

    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

    /**
    * @Classname OrderMain80
    * @Description chengzhi
    * @Created by chengzhi
    */
    @SpringBootApplication
    @EnableEurekaClient
    public class OrderMain80 {
    public static void main(String[] args) {
    SpringApplication.run(OrderMain80.class,args);
    }
    }

2、Eureka 集群构建步骤

集群原理说明

2-1、创建模块 cloud-eureka-server7002

与 7001 类似,就不多叙述了

第一步

找到 C:\Windows\System32\drivers\etc 路径下的 hosts 文件,修改映射配置添加进 hosts 文件,因为浏览器不识别 eureka7001.com,不添加会导致后面的服务找不到注册中心的地址。

修改 hosts 内容

1
2
3
4
5
#####springcloud2023项目试玩#########
127.0.0.1 eureka7001.com
127.0.0.1 eureka7002.com
127.0.0.1 eureka7003.com
####结束操作 springcloud2023项目试玩########

第二步:修改 yml

7001yml

主要配置 defaultZone: http://eureka7002.com:7002/eureka/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
server:
port: 7001

eureka:
instance:
hostname: localhost # eureka 服务端的实例名称

client:
# false 代表不向服务注册中心注册自己,因为它本身就是服务中心
register-with-eureka: false
# false 代表自己就是服务注册中心,自己的作用就是维护服务实例,并不需要去检索服务
fetch-registry: false
service-url:
# 设置与 Eureka Server 交互的地址,查询服务 和 注册服务都依赖这个地址 http://eureka7002.com:7002/eureka/
defaultZone: http://eureka7002.com:7002/eureka/

7002yml

主要配置 defaultZone: http://eureka7001.com:7001/eureka/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
server:
port: 7002

eureka:
instance:
hostname: localhost # eureka 服务端的实例名称

client:
# false 代表不向服务注册中心注册自己,因为它本身就是服务中心
register-with-eureka: false
# false 代表自己就是服务注册中心,自己的作用就是维护服务实例,并不需要去检索服务
fetch-registry: false
service-url:
# 设置与 Eureka Server 交互的地址,查询服务 和 注册服务都依赖这个地址 http://eureka7001.com:7001/eureka/
defaultZone: http://eureka7001.com:7001/eureka/

8001yml

主要配置 defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
server:
port: 8001

spring:
application:
name: cloud-payment-service # 项目名,也是注册的名字

datasource:
type: com.alibaba.druid.pool.DruidDataSource #当前数据源操作类型
driver-class-name: org.gjt.mm.mysql.Driver #mysql驱动包
url: jdbc:mysql://localhost:3306/springcloud2023?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
username: root
password: root

eureka:
client:
# 注册进 Eureka 的服务中心
register-with-eureka: true
# 检索服务中心的其它服务
# 单节点无所谓,集群必须设置为true才能配合ribbon使用负载均衡
fetch-registry: true
service-url:
# 设置与 Eureka Server 交互的地址
defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/

mybatis:
mapper-locations: classpath:mapper/*.xml
# 所有Entity 别名类所在包
type-aliases-package: com.jcvv.springcloud.entities

2-2、创建模块 cloud-provider-payment8002

  • pom 文件

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    <?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">
    <parent>
    <artifactId>springCloud2023</artifactId>
    <groupId>com.jcvv.springcloud</groupId>
    <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>cloud-provider-payment8002</artifactId>

    <properties>
    <maven.compiler.source>8</maven.compiler.source>
    <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <dependencies>
    <!-- 引入自己定义的api通用包,可以使用Payment支持Entity-->
    <dependency>
    <groupId>com.jcvv.springcloud</groupId>
    <artifactId>cloud-api-common</artifactId>
    <version>${project.version}</version>
    </dependency>
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- 图形化显示-->
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    </dependency>
    <dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.1.10</version>
    </dependency>
    <!--mysql-connector-java-->
    <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    </dependency>
    <!--jdbc-->
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <!-- devtools-->
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <scope>runtime</scope>
    <optional>true</optional>
    </dependency>
    <dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
    </dependency>
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
    </dependency>
    <!--eureka-client-->
    <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>
    </dependencies>
    </project>
  • 主启动类

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    package com.jcvv.springcloud;

    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

    /**
    * @Classname PaymentMain8002
    * @Description chengzhi
    * @Created by chengzhi
    */
    @SpringBootApplication
    @EnableEurekaClient
    public class PaymentMain8002 {
    public static void main(String[] args) {
    SpringApplication.run(PaymentMain8002.class, args);
    }
    }


  • application.yml

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    server:
    port: 8002

    spring:
    application:
    name: cloud-payment-service # 项目名,也是注册的名字

    datasource:
    type: com.alibaba.druid.pool.DruidDataSource #当前数据源操作类型
    driver-class-name: org.gjt.mm.mysql.Driver #mysql驱动包
    url: jdbc:mysql://localhost:3306/springcloud2023?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
    username: root
    password: root

    eureka:
    client:
    # 注册进 Eureka 的服务中心
    register-with-eureka: true
    # 检索服务中心的其它服务
    # 单节点无所谓,集群必须设置为true才能配合ribbon使用负载均衡
    fetch-registry: true
    service-url:
    # 设置与 Eureka Server 交互的地址
    defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/

    mybatis:
    mapper-locations: classpath:mapper/*.xml
    # 所有Entity 别名类所在包
    type-aliases-package: com.jcvv.springcloud.entities

2、其余于 8001 类似,请参中 8001 模块

3、修改 8001/8002 中的 controller 类

主要代码

1
2
@Value("${server.port}")
private String serverPort;

controller 类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package com.jcvv.springcloud.controller;

import com.jcvv.springcloud.entities.CommonResult;
import com.jcvv.springcloud.entities.Payment;
import com.jcvv.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
* @Classname PaymentController
* @Description chengzhi
* @Created by chengzhi
*/
@RestController
@Slf4j
public class PaymentController {
@Resource
private PaymentService paymentService;
@Value("${server.port}")
private String serverPort;

@PostMapping(value = "/payment/create")
public CommonResult create(@RequestBody Payment payment) {
int result = paymentService.create(payment);
log.info("*******插入结果" + result);
if (result > 0) {
return new CommonResult(200, "插入数据成功!"+serverPort,result);

} else {
return new CommonResult(444, "插入数据失败", null);
}
}

@GetMapping(value = "/payment/get/{id}")
public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id) {
Payment payment = paymentService.getPaymentById(id);
log.info("*******插入结果" + payment + "哈哈哈!!!");
if (payment != null) {
return new CommonResult(200, "查询成功!"+serverPort, payment);

} else {
return new CommonResult(444, "查询失败,没有对应记录", null);
}
}
}

4、对 cloud-consumer-order80 模块进行修改

controller 类

主要代码

1
public static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package com.jcvv.springcloud.controller;

import com.jcvv.springcloud.entities.CommonResult;
import com.jcvv.springcloud.entities.Payment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
* @Classname OrderController
* @Description chengzhi
* @Created by chengzhi
*/
@RestController
@Slf4j
public class OrderController {
//public static final String PAYMENT_URL = "http://localhost:8001";
public static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";
@Resource
private RestTemplate restTemplate;

/**
* @param payment
* @return
*/
@GetMapping("/consumer/payment/create")
public CommonResult<Payment> create(Payment payment) {
//payment 参数,CommonResult.class返回类型
return restTemplate.postForObject(PAYMENT_URL + "/payment/create", payment, CommonResult.class);

}

/**
*
* @param id
* @return
*/
@GetMapping("/consumer/payment/get/{id}")
public CommonResult<Payment> getPayment(@PathVariable("id") Long id) {
return restTemplate.getForObject(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);
}
}

ApplicationContextConfig 类

主要代码:使用 LoadBalanced 注解赋予 RestTemplate 负载均衡的能力

//使用 LoadBalanced 注解赋予 RestTemplate 负载均衡的能力
@LoadBalanced

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package com.jcvv.springcloud.config;

import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

/**
* @Classname ApplicationContextConfig
* @Description chengzhi
* @Created by chengzhi
*/
@Configuration
public class ApplicationContextConfig {
@Bean
//使用LoadBalanced注解赋予RestTemplate负载均衡的能力
@LoadBalanced
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
}

3、actuator微服务信息完善

含有主机名称设置

修改 8001 和 8002 yml 文件

8001 同理

1
2
instance:
instance-id: payment8002 # 每个提供者的id不同,显示的不再是默认的项目名
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
server:
port: 8001

spring:
application:
name: cloud-payment-service # 项目名,也是注册的名字

datasource:
type: com.alibaba.druid.pool.DruidDataSource #当前数据源操作类型
driver-class-name: org.gjt.mm.mysql.Driver #mysql驱动包
url: jdbc:mysql://localhost:3306/springcloud2023?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
username: root
password: root

eureka:
client:
# 注册进 Eureka 的服务中心
register-with-eureka: true
# 检索服务中心的其它服务
# 单节点无所谓,集群必须设置为true才能配合ribbon使用负载均衡
fetch-registry: true
service-url:
# 设置与 Eureka Server 交互的地址
defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/
instance:
instance-id: payment8002 # 每个提供者的id不同,显示的不再是默认的项目名

mybatis:
mapper-locations: classpath:mapper/*.xml
# 所有Entity 别名类所在包
type-aliases-package: com.jcvv.springcloud.entities

访问信息 P 信息提示配置

为了在微服务 Eureka 控制台能看到我们的某个具体服务是在哪台服务器上部署的,我们需要配置一些内容

修改 8001 和 8002 YAML 文件

主要代码

prefer-ip-address: true # 可以显示 ip 地址

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
server:
port: 8001

spring:
application:
name: cloud-payment-service # 项目名,也是注册的名字

datasource:
type: com.alibaba.druid.pool.DruidDataSource #当前数据源操作类型
driver-class-name: org.gjt.mm.mysql.Driver #mysql驱动包
url: jdbc:mysql://localhost:3306/springcloud2023?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
username: root
password: root

eureka:
client:
# 注册进 Eureka 的服务中心
register-with-eureka: true
# 检索服务中心的其它服务
# 单节点无所谓,集群必须设置为true才能配合ribbon使用负载均衡
fetch-registry: true
service-url:
# 设置与 Eureka Server 交互的地址
defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/
instance:
instance-id: payment8001 # 每个提供者的id不同,显示的不再是默认的项目名
prefer-ip-address: true # 可以显示ip地址

mybatis:
mapper-locations: classpath:mapper/*.xml
# 所有Entity 别名类所在包
type-aliases-package: com.jcvv.springcloud.entities

4、服务发现 Discovery

对于注册进 eureka 里面的微服务,可以通过服务发现来获得该服务的信息。

4-1、修改 8001 和 8002 的 Controller

添加以下内容

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package com.jcvv.springcloud.controller;

import com.jcvv.springcloud.entities.CommonResult;
import com.jcvv.springcloud.entities.Payment;
import com.jcvv.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
* @Classname PaymentController
* @Description chengzhi
* @Created by chengzhi
*/
@RestController
@Slf4j
public class PaymentController {
@Resource
private PaymentService paymentService;
@Value("${server.port}")
private String serverPort;
@Resource
private DiscoveryClient discoveryClient;
@PostMapping(value = "/payment/create")
public CommonResult create(@RequestBody Payment payment) {
int result = paymentService.create(payment);
log.info("*******插入结果" + result);
if (result > 0) {
return new CommonResult(200, "插入数据成功!"+serverPort,result);

} else {
return new CommonResult(444, "插入数据失败", null);
}
}

@GetMapping(value = "/payment/get/{id}")
public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id) {
Payment payment = paymentService.getPaymentById(id);
log.info("*******插入结果" + payment + "哈哈哈!!!");
if (payment != null) {
return new CommonResult(200, "查询成功!"+serverPort, payment);

} else {
return new CommonResult(444, "查询失败,没有对应记录", null);
}
}
@GetMapping(value = "/payment/discovery")
public Object discovery() {
//获得服务清单列表
List<String> services = discoveryClient.getServices();
for (String service : services) {
log.info("*****element:" + service);
}

// 根据具体服务进一步获得该微服务的信息
List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
for (ServiceInstance instance : instances) {
log.info(instance.getServiceId() + "\t" + instance.getHost() + "\t" + instance.getPort() + "\t" + instance.getUri());
}
return this.discoveryClient;
}
}

4-2、主启动类

主启动类上添加注解:@EnableDiscoveryClient

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.jcvv.springcloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

/**
* @Classname PaymentMain8001
* @Description chengzhi
* @Created by chengzhi
*/
@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
public class PaymentMain8001 {
public static void main(String[] args) {
SpringApplication.run(PaymentMain8001.class, args);
}
}

ps:在这里自己项目漏了一个东西,导致 cloud-consumer-order 为 unknow

修改 cloud-consumer-order80 模块中的 application.yaml

主要遗漏代码:

1
2
3
spring:
application:
name: cloud-consumer-order # 项目名,也是注册的名字
1
2
3
4
5
6
7
8
9
10
11
server:
port: 80
spring:
application:
name: cloud-consumer-order # 项目名,也是注册的名字
eureka:
client:
register-with-eureka: true
fetch-registry: true
service-url:
defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/

5、Eureka 自我保护

5-1、故障现象

概述

保护模式主要用于一组客户端和 Eureka Server 之间存在网络分区场景下的保护。一旦进入保护模式,Eureka Server 将会尝试保护其服务注册表中的信息,不再删除服务注册表中的数据,也就是不会注销任何微服务。

如果在 Eureka Server 的首页看到以下这段提示,则说明 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

5-2、什么是自我保护模式?

默认情况下,如果 EurekaServer 在一定时间内没有接收到某个微服务实例的心跳,EurekaServer 将会注销该实例(默认 90 秒)。但是当网络分区故障发生(延时、卡顿、拥挤)时,微服务与 EurekaServer 之间无法正常通信,以上行为可能变得非常危险了——因为微服务本身其实是健康的,此时本不应该注销这个微服务。Eureka 通过“自我保护模式”来解决这个问题——当 EurekaServer 节点在短时间内丢失过多客户端时(可能发生了网络分区故障),那么这个节点就会进入自我保护模式。

在自我保护模式中,Eureka Server 会保护服务注册表中的信息,不再注销任何服务实例。

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

一句话:某时刻某一个微服务不可用了,Eureka 不会立刻清理,依旧会对该微服务的信息进行保存

属于 CAP 里面的 AP 分支

5-3、怎么禁止自我保护

现在可以不用集群版了,只用开一个。

注册中心 eureakeServer 端 7001

出厂默认,自我保护机制是开启的 eureka.server.enable-self-preservation=true,使用 eureka.server.enable-self-preservation = false 可以禁用自我保护模式

1
2
3
4
server:
# 关闭自我保护机制,保证不可用该服务被及时剔除
enable-self-preservation: false
eviction-interval-timer-in-ms: 2000
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
server:
port: 7001

eureka:
instance:
hostname: eureka7001.com # eureka 服务端的实例名称

client:
# false 代表不向服务注册中心注册自己,因为它本身就是服务中心
register-with-eureka: false
# false 代表自己就是服务注册中心,自己的作用就是维护服务实例,并不需要去检索服务
fetch-registry: false
service-url:
# 设置与 Eureka Server 交互的地址,查询服务 和 注册服务都依赖这个地址
defaultZone: http://eureka7001.com:7001/eureka/
server:
# 关闭自我保护机制,保证不可用该服务被及时剔除
enable-self-preservation: false
eviction-interval-timer-in-ms: 2000

生产者客户端 eureakeClient 端 8001

1
2
3
4
# Eureka客户端像服务端发送心跳的时间间隔,单位s,默认30s
least-renewal-interval-in-seconds: 1
# Rureka服务端在收到最后一次心跳后等待时间上线,单位为s,默认90s,超时将剔除服务
least-expiration-duration-in-seconds: 2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
server:
port: 8001

spring:
application:
name: cloud-payment-service # 项目名,也是注册的名字
datasource:
type: com.alibaba.druid.pool.DruidDataSource #当前数据源操作类型
driver-class-name: org.gjt.mm.mysql.Driver #mysql驱动包
url: jdbc:mysql://localhost:3306/db2019?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
username: root
password: 12345

eureka:
client:
# 注册进 Eureka 的服务中心
register-with-eureka: true
# 检索 服务中心 的其它服务
fetch-registry: true
service-url:
# 设置与 Eureka Server 交互的地址
# 提供者注册到多个eureka中
defaultZone: http://eureka7001.com:7001/eureka/
# defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/
instance:
instance-id: payment8001 # 每个提供者的id不同,显示的不再是默认的项目名
prefer-ip-address:
true # 可以显示ip地址
# Eureka客户端像服务端发送心跳的时间间隔,单位s,默认30s
least-renewal-interval-in-seconds:
1
# Rureka服务端在收到最后一次心跳后等待时间上线,单位为s,默认90s,超时将剔除服务
least-expiration-duration-in-seconds: 2

mybatis:
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.atguigu.springcloud.entities # 所有Entity 别名类所在包

测试

先启动 7001 再启动 8001,关闭 8001,马上被删除了

Eureka 停更说明:2.0 后停更了。
相关链接:zookeeper服务注册中心😶