Eureka学习

336 阅读13分钟

一、Eureka基础知识

1、什么是服务治理

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

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

2、什么是服务注册与发现

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

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

3、Eureka两个组件

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

(1)、Eureka Server提供服务注册服务

各个微服务节点通过配置启动后,会在EurekaServer中进行注册,这样EurekaServer中的服务注册表中会存储所有可用的服务节的信息,服务节点的信息可以在界面中直观看到。

(2)、Eureka Client通过注册中心进行访问

是一个Java客户端,用于简化Eureka Server的交互,客户端同时也具备衣蛾内置的,使用伦旭(round-robin)负载算法的负载均衡器。在应用启动后,将会想Eureka Server发送心跳(默认是30秒钟)。如果Eureka Server在多个心跳周期内没有收到某个节点的心跳,Eureka Server将会从服务注册表中吧这个节点移除(默认90秒)。

二、单机Eureka构建步骤

1、构建准备工作

(1)、创建项目minhat-cloud

  • 项目名称:minhat-cloud
  • 包名:cn.minhat.cloud

(2)、修改pom文件

<?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>cn.minhat.cloud</groupId>
    <artifactId>minhat-cloud</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>pom</packaging>

    <!-- 统一管理jar包 -->
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <junit.version>4.12</junit.version>
        <log4j.version>1.2.17</log4j.version>
        <lombok.version>1.16.18</lombok.version>
        <mysql.version>8.0.21</mysql.version>
        <druid.version>1.1.16</druid.version>
        <mybatis.spring.boot.version>1.3.0</mybatis.spring.boot.version>
    </properties>

    <dependencyManagement>
        <dependencies>
            <!-- SpringBoot 2.2.2 -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>2.2.2.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!-- Spring Cloud Hoxton.SR1 -->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Hoxton.SR1</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>${mysql.version}</version>
            </dependency>
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid-spring-boot-starter</artifactId>
                <version>${druid.version}</version>
            </dependency>
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>${mybatis.spring.boot.version}</version>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.2.2.RELEASE</version>
                <configuration>
                    <fork>true</fork>
                    <addResources>true</addResources>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

(3)、建库、建表和初始化数据

-- 创建数据库
CREATE DATABASE `minhat-cloud` CHARACTER SET 'utf8mb4' COLLATE 'utf8mb4_general_ci'

-- 创建表
CREATE TABLE `minhat-cloud`.`product_order` (
  `id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键',
  `product_name` varchar(255) COLLATE utf8mb4_general_ci NOT NULL COMMENT '商品名称',
  `price` bigint NOT NULL COMMENT '单价价格',
  `status` int NOT NULL COMMENT '状态,1:已支付,2:未支付',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='商品订单';

-- 初始化数据
INSERT INTO `minhat-cloud`.`product_order` (`id`, `product_name`, `price`, `status`) VALUES (1, 'Java编程思想', 9800, 1);
INSERT INTO `minhat-cloud`.`product_order` (`id`, `product_name`, `price`, `status`) VALUES (2, 'Java虚拟机', 7800, 2);

2、创建公共模块 cloud-commons

公共模块包含实体类和公共反回类

(1)、修改pom文件

<?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>minhat-cloud</artifactId>
        <groupId>cn.minhat.cloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>cloud-commons</artifactId>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>
</project>

(2)、创建实体类

/**
 * 商品订单
 *
 * @author Minhat
 */
@Data
@Accessors(chain = true)
@AllArgsConstructor
@NoArgsConstructor
public class ProductOrder {
    /**
     * 主键
     */
    private Long id;
    /**
     * 商品名称
     */
    private String productName;
    /**
     * 单价价格
     */
    private Long price;
    /**
     * 状态,1:已支付,2:未支付
     */
    private Integer status;
    
    public ProductOrder(String productName, Long price, Integer status) {
        this.productName = productName;
        this.price = price;
        this.status = status;
    }
}


/**
 * 公共结果返回
 *
 * @author Minhat
 */
@Data
@Accessors(chain = true)
@AllArgsConstructor
@NoArgsConstructor
public class CommonsResult<T> {
    private Integer code;
    private String msg;
    private T data;

    public CommonsResult(Integer code, String msg) {
        this.code = code;
        this.msg = msg;
    }
}

3、创建EurekaServer微服务注册中心 cloud-eureka-server

(1)、修改pom文件

<?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>minhat-cloud</artifactId>
        <groupId>cn.minhat.cloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>cloud-eureka-server</artifactId>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <dependencies>
        <!-- Eureka-Server -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>
        <!-- boot web actuator -->
        <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>

(2)、改application.yml

如果没有application.yml自行创建

server:
  port: 7001

# EurekaServer配置
eureka:
  instance:
    # eureka服务端的实例名称
    hostname: localhost
  client:
    # false表示不向注册中心注册自己
    register-with-eureka: false
    # false表示自己端就是注册中心,我的职责就是维护服务实例,并不需要去检索服务
    fetch-registry: false
    service-url:
      # 设置与Eureka Server交互的地址查询服务和注册服务都需要这地址
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/

(3)、创建主启动类

@EnableEurekaServer:启用EurekaServer

/**
 * EurekaServer启动类
 * EnableEurekaServer:启用EurekaServer
 *
 * @author Minhat
 */
@SpringBootApplication
@EnableEurekaServer
public class CloudEurekaServer {
    public static void main(String[] args) {
        SpringApplication.run(CloudEurekaServer.class, args);
    }
}

(4)、启动EurekaServer并查看监控界面

1>、启动EurekaServer

2>、查看启动

请求:http://localhost:7001/ image.png

4、创建EurekaClient端订单提供者 cloud-eureka-order-client

(1)、修改pom文件

<?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>minhat-cloud</artifactId>
        <groupId>cn.minhat.cloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>cloud-eureka-order-client</artifactId>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <dependencies>
        <!-- Eureka Client -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <!-- 自己定义的公共模块 -->
        <dependency>
            <groupId>cn.minhat.cloud</groupId>
            <artifactId>cloud-commons</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>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <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>
    </dependencies>
</project>

(2)、改application.yml

server:
  port: 8001

spring:
  application:
    # 微服务名称
    name: cloud-eureka-order-client
  datasource:
    # 当前数据源操作类型
    type: com.alibaba.druid.pool.DruidDataSource
    # Mysql启动包
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/cloud-minhat?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
    username: root
    password: 123456

eureka:
  client:
    # 表示是否将自己注册进EurekaServer默认true
    register-with-eureka: true
    # 是否从EurekaServer抓取已有的注册信息,默认是true,单节点无所谓,集群必须设置为true才能够配合Ribbon使用负载均衡
    fetch-registry: true
    service-url:
      defaultZone: http://localhost:7001/eureka

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

(3)、创建主启动类

@EnableEurekaClient:启用EurekaClient

/**
 * 订单微服务主启动类
 *
 * @author Minhat
 */
@SpringBootApplication
@EnableEurekaClient
public class CloudEurekaOrderClient {
    public static void main(String[] args) {
        SpringApplication.run(CloudEurekaOrderClient.class, args);
    }
}

(4)、创建DAO接口和Mapper

DAO接口:

/**
 * 订单DAO
 *
 * @author Minhat
 */
@Mapper
public interface IProductOrderDao {

    /**
     * 根据订单实体图插入订单
     *
     * @param productOrder 订单
     * @return 返回受影响行数
     */
    Integer insertByProductOrder(ProductOrder productOrder);

    /**
     * 根据订单id查询订单
     *
     * @param id 订单id
     * @return 订单
     */
    ProductOrder selectByProductOrderId(long id);
}

Mapper:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.minhat.cloud.dao.IProductOrderDao">
    <resultMap id="BaseResultMap" type="cn.minhat.cloud.entities.ProductOrder">
        <id column="id" jdbcType="BIGINT" property="id"/>
        <result column="product_name" jdbcType="VARCHAR" property="productName"/>
        <result column="price" jdbcType="BIGINT" property="price"/>
        <result column="status" jdbcType="INTEGER" property="status"/>
    </resultMap>

    <sql id="Base_Column_List">
        `id`, `product_name`, `price`, `status`
    </sql>

    <insert id="insertByProductOrder" useGeneratedKeys="true" keyColumn="id" keyProperty="id" parameterType="cn.minhat.cloud.entities.ProductOrder">
        insert into product_order(`product_name`, `price`, `status`)
        values (#{productName,jdbcType=VARCHAR}, #{price,jdbcType=BIGINT}, #{status,jdbcType=INTEGER})
    </insert>

    <select id="selectByProductOrderId" parameterType="java.lang.Long" resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List"/>
        from product_order
        where id = #{id,jdbcType=BIGINT}
    </select>

</mapper>

(5)、创建Server层

Server层接口:

/**
 * 订单Server接口
 *
 * @author Minhat
 */
public interface IProductOrderServer {
    /**
     * 根据订单实体图插入订单
     *
     * @param productOrder 订单
     * @return 返回受影响行数
     */
    Integer insertByProductOrder(ProductOrder productOrder);

    /**
     * 根据订单id查询订单
     *
     * @param id 订单id
     * @return 订单
     */
    ProductOrder selectByProductOrderId(long id);
}

Server层接口实现:

/**
 * 订单Server接口实现类
 *
 * @author Minhat
 */
@Service
public class ProductOrderServerImpl implements IProductOrderServer {
    @Autowired
    private IProductOrderDao productOrderDao;

    @Override
    public Integer insertByProductOrder(ProductOrder productOrder) {
        return productOrderDao.insertByProductOrder(productOrder);
    }

    @Override
    public ProductOrder selectByProductOrderId(long id) {
        return productOrderDao.selectByProductOrderId(id);
    }
}

(6)、创建Controller层

/**
 * 订单Controller
 *
 * @author Minhat
 */
@RestController
@RequestMapping("/order")
public class ProductOrderController {
    @Autowired
    private IProductOrderServer productOrderServer;

    @PostMapping("/add")
    public CommonsResult<ProductOrder> add(@RequestBody ProductOrder productOrder) {
        productOrderServer.insertByProductOrder(productOrder);
        return new CommonsResult<>(0, "添加成功", productOrder);
    }

    @GetMapping("find/{id}")
    public CommonsResult<ProductOrder> find(@PathVariable Integer id) {
        ProductOrder productOrder = productOrderServer.selectByProductOrderId(id);
        return new CommonsResult<>(0, "查询成功", productOrder);
    }
}

(7)、测试

1>、启动项目

  1. 启动:cloud-eureka-server
  2. 启动:cloud-eureka-order-client

2>、访问Eureka监控界面

请求:http://localhost:7001/ image.png

3>、请求Controller的接口

请求:http://localhost:8001/order/find/1 image.png

请求:http://localhost:8001/order/add image.png

5、创建EurekaClient端消费者 cloud-eureka-consumer-client

(1)、修改pom文件

<?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>minhat-cloud</artifactId>
        <groupId>cn.minhat.cloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>cloud-eureka-consumer-client</artifactId>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <dependencies>
        <!-- Eureka Client -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <!-- 自己定义的公共模块 -->
        <dependency>
            <groupId>cn.minhat.cloud</groupId>
            <artifactId>cloud-commons</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.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>
    </dependencies>

</project>

(2)、改application.yml

server:
  port: 80

spring:
  application:
    # 微服务名称
    name: cloud-eureka-consumer-client

eureka:
  client:
    # 表示是否将自己注册进EurekaServer默认true
    register-with-eureka: true
    # 是否从EurekaServer抓取已有的注册信息,默认是true,单节点无所谓,集群必须设置为true才能够配合Ribbon使用负载均衡
    fetch-registry: true
    service-url:
      defaultZone: http://localhost:7001/eureka

(3)、创建主启动类

/**
 * 消费者微服务启动类
 * @author Minhat
 */
@SpringBootApplication
@EnableEurekaClient
public class CloudEurekaConsumerClient {
    public static void main(String[] args) {
        SpringApplication.run(CloudEurekaConsumerClient.class, args);
    }
}

(4)、添加配置类

/**
 * 配置类
 *
 * @author Minhat
 */
@Configuration
public class ApplicationContextConfig {
    @Bean
    public RestTemplate getRestTemplate() {
        return new RestTemplate();
    }
}

(5)、创建Controller

@EnableEurekaClient:启用EurekaClient

/**
 * 订单消费者Controller
 *
 * @author Minhat
 */
@RestController
@RequestMapping("/consumer/order")
public class ConsumerOrderController {
    public static final String PAYMENT_URL = "http://localhost:8001";

    @Autowired
    private RestTemplate restTemplate;

    @PostMapping("/add")
    public CommonsResult<ProductOrder> add(@RequestBody ProductOrder productOrder) {
        CommonsResult<ProductOrder> commonsResult = restTemplate.postForObject(PAYMENT_URL + "/order/add/", productOrder, CommonsResult.class);
        return new CommonsResult<>(0, "添加成功", commonsResult.getData());
    }

    @GetMapping("find/{id}")
    public CommonsResult<ProductOrder> find(@PathVariable Integer id) {
        return restTemplate.getForObject(PAYMENT_URL + "/order/find/" + id, CommonsResult.class);
    }
}

(6)、测试

1>、启动项目

  1. 启动:cloud-eureka-server
  2. 启动:cloud-eureka-order-client
  3. 启动:cloud-eureka-consumer-client

2>、访问Eureka监控界面

请求:http://localhost:7001/ image.png

3>、请求消费者Controller的接口

请求:http://localhost:80/consumer/order/find/2 image.png 请求:http://localhost:80/consumer/order/add image.png

三、集群Eureka构建步骤

1、Eureka集群原理说明

Eureka集群原理说明.png

问题:微服务RPC远程调用最核心的是什么 高可用,试想一下你的注册中心只有一个,如果它出故障了,哈酒呵呵o( ̄︶ ̄)o了,会导致整个服务环境不可用,所以解决办法是:搭建Eureka注册中心集群,实现负载均衡+故障容错

2、修改映射配置

找到C:\Windows\System32\drivers\etc路径下的hosts文件进行修改 image.png 此配置是添加主机映射地址

3、EurekaServer集群配置

(1)、添加application-7001.yml配置文件

server:
  port: 8001

spring:
  application:
    # 微服务名称
    name: cloud-eureka-order-client
  datasource:
    # 当前数据源操作类型
    type: com.alibaba.druid.pool.DruidDataSource
    # Mysql启动包
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/minhat-cloud?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
    username: root
    password: 123456

eureka:
  client:
    # 表示是否将自己注册进EurekaServer默认true
    register-with-eureka: true
    # 是否从EurekaServer抓取已有的注册信息,默认是true,单节点无所谓,集群必须设置为true才能够配合Ribbon使用负载均衡
    fetch-registry: true
    service-url:
      # Eureka集群配置
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/

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

(2)、添加application-7002.yml配置文件

server:
  port: 8002

spring:
  application:
    # 微服务名称
    name: cloud-eureka-order-client
  datasource:
    # 当前数据源操作类型
    type: com.alibaba.druid.pool.DruidDataSource
    # Mysql启动包
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/minhat-cloud?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
    username: root
    password: 123456

eureka:
  client:
    # 表示是否将自己注册进EurekaServer默认true
    register-with-eureka: true
    # 是否从EurekaServer抓取已有的注册信息,默认是true,单节点无所谓,集群必须设置为true才能够配合Ribbon使用负载均衡
    fetch-registry: true
    service-url:
      # Eureka集群配置
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/

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

(3)、启动前配置

点击配置启动类: image.png 配置启动环境CloudEurekaServer-7001: image.png 配置启动环境CloudEurekaServer-7002: image.png

(4)、测试

1>、启动项目

  • CloudEurekaServer-7001
  • CloudEurekaServer-7002

2>、访问Eureka监控界面

访问:CloudEurekaServer-7001 eureka7001.com:7001/ image.png

访问:CloudEurekaServer-7002 eureka7002.com:7002/ image.png

4、EurekaClient端订单提供者 cloud-eureka-order-client 集群

(1)、添加application-8001.yml配置文件

server:
  port: 8001

spring:
  application:
    # 微服务名称
    name: cloud-eureka-order-client
  datasource:
    # 当前数据源操作类型
    type: com.alibaba.druid.pool.DruidDataSource
    # Mysql启动包
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/minhat-cloud?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
    username: root
    password: 123456

eureka:
  client:
    # 表示是否将自己注册进EurekaServer默认true
    register-with-eureka: true
    # 是否从EurekaServer抓取已有的注册信息,默认是true,单节点无所谓,集群必须设置为true才能够配合Ribbon使用负载均衡
    fetch-registry: true
    service-url:
      # Eureka集群配置
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/

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

(2)、添加application-8002.yml配置文件

server:
  port: 8002

spring:
  application:
    # 微服务名称
    name: cloud-eureka-order-client
  datasource:
    # 当前数据源操作类型
    type: com.alibaba.druid.pool.DruidDataSource
    # Mysql启动包
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/minhat-cloud?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
    username: root
    password: 123456

eureka:
  client:
    # 表示是否将自己注册进EurekaServer默认true
    register-with-eureka: true
    # 是否从EurekaServer抓取已有的注册信息,默认是true,单节点无所谓,集群必须设置为true才能够配合Ribbon使用负载均衡
    fetch-registry: true
    service-url:
      # Eureka集群配置
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/

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

(3)、修改Controller层

/**
 * 订单Controller
 *
 * @author Minhat
 */
@RestController
@RequestMapping("/order")
public class ProductOrderController {
    @Autowired
    private IProductOrderServer productOrderServer;
    @Value("${server.port}")
    private String serverPort;

    @PostMapping("/add")
    public CommonsResult<ProductOrder> add(@RequestBody ProductOrder productOrder) {
        productOrderServer.insertByProductOrder(productOrder);
        return new CommonsResult<>(0, "添加成功-端口:" + serverPort, productOrder);
    }

    @GetMapping("find/{id}")
    public CommonsResult<ProductOrder> find(@PathVariable Integer id) {
        ProductOrder productOrder = productOrderServer.selectByProductOrderId(id);
        return new CommonsResult<>(0, "查询成功-端口:" + serverPort, productOrder);
    }
}

(4)、启动前配置

点击配置启动类: image.png 配置启动环境CloudEurekaOrderClient-8001: image.png 配置启动环境CloudEurekaOrderClient-8002: image.png

(5)、测试

1>、启动项目

  • CloudEurekaServer-7001
  • CloudEurekaServer-7002
  • CloudEurekaOrderClient-8001
  • CloudEurekaOrderClient-8002

2>、访问Eureka监控界面

访问:CloudEurekaServer-7001 eureka7001.com:7001/ image.png 访问:CloudEurekaServer-7002 eureka7002.com:7002/ image.png

2>、访问CloudEurekaOrderClient两个微服务Order

访问:CloudEurekaOrderClient-8001 image.png 访问:CloudEurekaOrderClient-8002 image.png

5、EurekaClient端消费者 cloud-eureka-consumer-client调用集群订单微服务

(1)、修改application.yml配置文件

server:
  port: 80

spring:
  application:
    # 微服务名称
    name: cloud-eureka-consumer-client

eureka:
  client:
    # 表示是否将自己注册进EurekaServer默认true
    register-with-eureka: true
    # 是否从EurekaServer抓取已有的注册信息,默认是true,单节点无所谓,集群必须设置为true才能够配合Ribbon使用负载均衡
    fetch-registry: true
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/

(2)、修改ApplicationContextConfig配置类

/**
 * 配置类
 *
 * @author Minhat
 */
@Configuration
public class ApplicationContextConfig {
    @Bean
    @LoadBalanced
    public RestTemplate getRestTemplate() {
        return new RestTemplate();
    }
}

(3)、修改ConsumerOrderController配置类

/**
 * 订单消费者Controller
 *
 * @author Minhat
 */
@RestController
@RequestMapping("/consumer/order")
public class ConsumerOrderController {
    // public static final String PAYMENT_URL = "http://localhost:8001";
    public static final String PAYMENT_URL = "http://CLOUD-EUREKA-ORDER-CLIENT";

    @Autowired
    private RestTemplate restTemplate;

    @PostMapping("/add")
    public CommonsResult<ProductOrder> add(@RequestBody ProductOrder productOrder) {
        return restTemplate.postForObject(PAYMENT_URL + "/order/add/", productOrder, CommonsResult.class);
    }

    @GetMapping("find/{id}")
    public CommonsResult<ProductOrder> find(@PathVariable Integer id) {
        return restTemplate.getForObject(PAYMENT_URL + "/order/find/" + id, CommonsResult.class);
    }
}

(5)、测试

1>、启动项目

  • CloudEurekaServer-7001
  • CloudEurekaServer-7002
  • CloudEurekaOrderClient-8001
  • CloudEurekaOrderClient-8002
  • CloudEurekaConsumerClient

2>、访问Eureka监控界面

访问:CloudEurekaServer-7001 eureka7001.com:7001/ image.png 访问:CloudEurekaServer-7002 eureka7002.com:7002/ image.png

2>、访问CloudEurekaConsumerClient

第一次访问: image.png 第二次访问: image.png 第三次访问: image.png

四、Actuator服务信息完善

1、EurekaClient端订单提供者 cloud-eureka-order-client 配置

(1)、修改application-8001.yml配置文件

server:
  port: 8001

spring:
  application:
    # 微服务名称
    name: cloud-eureka-order-client
  datasource:
    # 当前数据源操作类型
    type: com.alibaba.druid.pool.DruidDataSource
    # Mysql启动包
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/minhat-cloud?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
    username: root
    password: 123456

eureka:
  client:
    # 表示是否将自己注册进EurekaServer默认true
    register-with-eureka: true
    # 是否从EurekaServer抓取已有的注册信息,默认是true,单节点无所谓,集群必须设置为true才能够配合Ribbon使用负载均衡
    fetch-registry: true
    service-url:
      # Eureka集群配置
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/
  instance:
    # 主机名称:服务名称修改
    instance-id: cloud-eureka-order-client-8001
    # 应优先使用服务器的 IP 地址,而不是操作系统报告的主机名
    prefer-ip-address: true

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

(2)、修改application-8002.yml配置文件

server:
  port: 8002

spring:
  application:
    # 微服务名称
    name: cloud-eureka-order-client
  datasource:
    # 当前数据源操作类型
    type: com.alibaba.druid.pool.DruidDataSource
    # Mysql启动包
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/minhat-cloud?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
    username: root
    password: 123456

eureka:
  client:
    # 表示是否将自己注册进EurekaServer默认true
    register-with-eureka: true
    # 是否从EurekaServer抓取已有的注册信息,默认是true,单节点无所谓,集群必须设置为true才能够配合Ribbon使用负载均衡
    fetch-registry: true
    service-url:
      # Eureka集群配置
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/
  instance:
    # 主机名称:服务名称修改
    instance-id: cloud-eureka-order-client-8002
    # 应优先使用服务器的 IP 地址,而不是操作系统报告的主机名
    prefer-ip-address: true

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

2、测试

(1)、启动项目

  • CloudEurekaServer-7001
  • CloudEurekaServer-7002
  • CloudEurekaOrderClient-8001
  • CloudEurekaOrderClient-8002

(2)、访问Eureka监控界面

访问:CloudEurekaServer-7001 eureka7001.com:7001/ image.png

五、服务发现Discovery

1、EurekaClient端订单提供者 cloud-eureka-order-client 修改

(1)、修改Controller

/**
 * 订单Controller
 *
 * @author Minhat
 */
@RestController
@RequestMapping("/order")
public class ProductOrderController {
    private static final Logger log = LoggerFactory.getLogger(ProductOrderController.class);
    @Autowired
    private IProductOrderServer productOrderServer;
    @Value("${server.port}")
    private String serverPort;
    /**
     * 通常可用于发现服务(例如 Netflix Eureka 或 consul.io)的读取操作
     */
    @Autowired
    private DiscoveryClient discoveryClient;

    @PostMapping("/add")
    public CommonsResult<ProductOrder> add(@RequestBody ProductOrder productOrder) {
        productOrderServer.insertByProductOrder(productOrder);
        return new CommonsResult<>(0, "添加成功-端口:" + serverPort, productOrder);
    }

    @GetMapping("find/{id}")
    public CommonsResult<ProductOrder> find(@PathVariable Integer id) {
        ProductOrder productOrder = productOrderServer.selectByProductOrderId(id);
        return new CommonsResult<>(0, "查询成功-端口:" + serverPort, productOrder);
    }

    @GetMapping("/discovery")
    public Object discovery() {
        // 获取已知的服务ID
        List<String> services = discoveryClient.getServices();
        services.forEach(s -> log.info("服务ID:{}", s));
        services.forEach(s -> {
            List<ServiceInstance> instances = discoveryClient.getInstances(s);
            instances.forEach(serviceInstance -> {
                log.info("ServiceId:{}\tInstanceId:{}\tHost:{}\tPort:{} \tScheme:{}", serviceInstance.getServiceId(), serviceInstance.getInstanceId(), serviceInstance.getHost(), serviceInstance.getPort(), serviceInstance.getScheme());
            });
        });
        return discoveryClient;
    }
}

(2)、修改主启动类

/**
 * 订单微服务主启动类
 *
 * @author Minhat
 */
@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
public class CloudEurekaOrderClient {
    public static void main(String[] args) {
        SpringApplication.run(CloudEurekaOrderClient.class, args);
    }
}

2、测试

(1)、启动项目

  • CloudEurekaServer-7001
  • CloudEurekaServer-7002
  • CloudEurekaOrderClient-8001
  • CloudEurekaOrderClient-8002
  • CloudEurekaConsumerClient

启动后稍等一会儿

(2)、CloudEurekaOrderClient-8001

http://localhost:8001/order/discovery image.png 查看CloudEurekaOrderClient-8001控制台 image.png

六、Eureka自我保护

1、故障现象

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

如果在EurekaServer的首页看到一下提示,则说明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. image.png

2、导致原因

(1)、为什么会产生Eureka自我保护机制?

为了防止EurekaClient可以正常运行,但是与EurekaServer网络不同情况,EurekaServer不会立刻将EurekaClient服务踢出。

(2)、什么是自我保护模式

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

Eureka自我保护机制.png

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

他的设计哲学就是宁可保留错误的服务注册信息,也不盲目注销任何可能健康的服务实例。一句话理解:好死不如赖活。

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

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

3、禁用Eureka自我保护

(1)、EurekaServer配置

application-7001.yml:

server:
  port: 7001

# EurekaServer配置
eureka:
  instance:
    # eureka服务端的实例名称
    hostname: eureka7001.com
  client:
    # false表示不向注册中心注册自己
    register-with-eureka: false
    # false表示自己端就是注册中心,我的职责就是维护服务实例,并不需要去检索服务
    fetch-registry: false
    service-url:
      # 设置与Eureka Server交互的地址查询服务和注册服务都需要这地址
      defaultZone: http://eureka7002.com:7002/eureka/
  server:
    # 关闭自我保护机制,保证不可用服务被及时踢出
    enable-self-preservation: false
    # 踢出不可用服务间隔毫秒
    eviction-interval-timer-in-ms: 2000

application-7002.yml:

server:
  port: 7002

# EurekaServer配置
eureka:
  instance:
    # eureka服务端的实例名称
    hostname: eureka7002.com
  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

(2)、EurekaClient端订单提供者 cloud-eureka-order-client 配置

application-8001.yml:

server:
  port: 8001

spring:
  application:
    # 微服务名称
    name: cloud-eureka-order-client
  datasource:
    # 当前数据源操作类型
    type: com.alibaba.druid.pool.DruidDataSource
    # Mysql启动包
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/minhat-cloud?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
    username: root
    password: 123456

eureka:
  client:
    # 表示是否将自己注册进EurekaServer默认true
    register-with-eureka: true
    # 是否从EurekaServer抓取已有的注册信息,默认是true,单节点无所谓,集群必须设置为true才能够配合Ribbon使用负载均衡
    fetch-registry: true
    service-url:
      # Eureka集群配置
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/
  instance:
    # 主机名称:服务名称修改
    instance-id: cloud-eureka-order-client-8001
    # 应优先使用服务器的 IP 地址,而不是操作系统报告的主机名
    prefer-ip-address: true
    # Eureka客户端向服务端发送心跳的时间间隔,单位为秒(默认30秒)
    lease-renewal-interval-in-seconds: 1
    # Eureka服务端在收到最后一次心跳后等待时间上限,单位秒(默认90秒),超时将踢出服务
    lease-expiration-duration-in-seconds: 2

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

application-8002.yml:

server:
  port: 8002

spring:
  application:
    # 微服务名称
    name: cloud-eureka-order-client
  datasource:
    # 当前数据源操作类型
    type: com.alibaba.druid.pool.DruidDataSource
    # Mysql启动包
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/minhat-cloud?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
    username: root
    password: 123456

eureka:
  client:
    # 表示是否将自己注册进EurekaServer默认true
    register-with-eureka: true
    # 是否从EurekaServer抓取已有的注册信息,默认是true,单节点无所谓,集群必须设置为true才能够配合Ribbon使用负载均衡
    fetch-registry: true
    service-url:
      # Eureka集群配置
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/
  instance:
    # 主机名称:服务名称修改
    instance-id: cloud-eureka-order-client-8002
    # 应优先使用服务器的 IP 地址,而不是操作系统报告的主机名
    prefer-ip-address: true
    # Eureka客户端向服务端发送心跳的时间间隔,单位为秒(默认30秒)
    lease-renewal-interval-in-seconds: 1
    # Eureka服务端在收到最后一次心跳后等待时间上限,单位秒(默认90秒),超时将踢出服务
    lease-expiration-duration-in-seconds: 2

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

4、测试

(1)、启动项目

  • CloudEurekaServer-7001
  • CloudEurekaServer-7002
  • CloudEurekaOrderClient-8001
  • CloudEurekaOrderClient-8002

(2)、访问Eureka健康界面

eureka7001.com:7001/ image.png

(3)、关闭CloudEurekaOrderClient-8002再查看健康界面

image.png