zoukankan      html  css  js  c++  java
  • Eureka 服务注册与发现

    一、Eureka 基础知识

    1、什么是服务治理

    SpringCloud 封装了 Netflix 公司开发的 Eureka 模块来实现服务治理。在传统的RPC远程调用框架中,管理每个服务与服务之间依赖关系比较复杂,管理比较杂,所以需要使用服务治理,管理服务与服务之间依赖关系,可以实现服务调用、负载均衡、容错等,实现服务发现与注册。

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

    Eureka 采用了CS的设计架构。Eureka Server 作为服务注册功能的服务器,它是服务注册中心。而系统中的其他微服务使用Eureka的客户端连接到 Eureka Server 并维持心跳连接。这样系统的维护人员就可以通过 Eureka Server 来监控系统中各个微服务是否正常运行。在服务注册与发现中,有一个注册中心。当服务器启动的时候,会把当前自己服务器的信息比如服务地址、通讯地址等以别名方式注册到注册中心上。另一方(消费者|服务提供者)以该别名的方式去注册中心上获取到实际的服务通信地址,然后RPC调用。RPC远程调用框架核心设计思想在于注册中心。使用注册中心管理每个服务与服务之间的一个依赖关系(服务治理概念)。在任何RPC远程框架中,都会有注册中心(存放服务地址相关信息(接口地址))

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

    Eureka Server 提供服务注册服务

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

    Eureka Client 通过注册中心进行访问

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

    二、单机Eureka构建步骤

    1、生成Eureka Server端

    1)建Module:cloud-eureka-server7001

    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">
        <parent>
            <artifactId>cloud2020</artifactId>
            <groupId>com.atguigu.springcloud</groupId>
            <version>1.0-SNAPSHOT</version>
        </parent>
        <modelVersion>4.0.0</modelVersion>
    
        <artifactId>cloud-eureka-server7001</artifactId>
    
        <dependencies>
            <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-eureka-server -->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
            </dependency>
    
            <dependency>
                <groupId>com.atguigu.springcloud</groupId>
                <artifactId>cloud-api-commons</artifactId>
                <version>${project.version}</version>
            </dependency>
    
            <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
    
            <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web  -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-actuator</artifactId>
            </dependency>
    
            <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-devtools -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-devtools</artifactId>
                <scope>runtime</scope>
                <optional>true</optional>
            </dependency>
    
            <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
            </dependency>
    
            <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-test -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
            </dependency>
    
        </dependencies>
    </project>
     
    pom文件

    注意区别

    以前的版本(当前使用2018)
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-eureka</artifactId>
    </dependency>
    
    现在新版本(当前使用2020.2<dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
    </dependency>

    3)写yml,注意不同版本之间key可能不一样

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

    4)主启动:注意@EnableEurekaServer注解

    package com.atguigu.springcloud;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
    
    @EnableEurekaServer
    @SpringBootApplication
    public class EurekaMain7001 {
        public static void main(String[] args) {
            SpringApplication.run(EurekaMain7001.class,args);
        }
    }

    5)测试:http://localhost:7001/

    2、生成Eureka Client端

    1)改pom

    <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-eureka-server -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>
    pom文件

    2)写yml

    eureka:
      client:
        register-with-eureka: true
        fetchRegistry: true
        service-url:
          defaultZone: http://localhost:7001/eureka
    yml文件

    3)主启动类加注解:@EnableEurekaClient

    4)测试

    三、集群Eureka构建步骤

    1、Eureka集群原理说明

    解决办法:搭建Eureka注册中心集群,实现负载均衡+故障容错

    2、EurekaServer 集群环境构建步骤

    1)参考cloud-eureka-server7001,新建cloud-eureka-server7002

    2)改POM

    3)修改映射配置

    找到C:WindowsSystem32driversetc路径下的hosts文件

    修改映射配置添加进hosts文件

    • 127.0.0.1  eureka7001.com
    • 127.0.0.1  eureka7002.com

    4)写yml

    #cloud-eureka-server7001 yml文件如下
    server:
      port: 7001
    
    eureka:
      instance:
        hostname: eureka7001.com    #eureka服务端的实例名字
      client:
        register-with-eureka: false    #表识不向注册中心注册自己
        fetch-registry: false   #表示自己就是注册中心,职责是维护服务实例,并不需要去检索服务
        service-url:
          defaultZone: http://eureka7002.com:7002/eureka/    #设置与eureka server交互的地址查询服务和注册服务都需要依赖这个地址
     
     
    #cloud-eureka-server7002 yml文件如下
    server:
      port: 7002
    
    eureka:
      instance:
        hostname: eureka7002.com #eureka服务端的实例名字
      client:
        register-with-eureka: false    #表识不向注册中心注册自己
        fetch-registry: false   #表示自己就是注册中心,职责是维护服务实例,并不需要去检索服务
        service-url:
          defaultZone: http://eureka7001.com:7001/eureka/     #设置与eureka server交互的地址查询服务和注册服务都需要依赖这个地址

    5)主启动(复制cloud-eureka-server7001的主启动类到7002即可)

    3、发布微服务到集群上

    service-url:
      defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka  #集群版

    4、测试

    1. 先要启动EurekaServer,7001/7002服务
    2. 再要启动服务提供者provider,8001服务
    3. 再要启动消费者,80
    4. http://localhost/consumer/payment/get/31

    5、支付服务提供者8001集群环境构建

    1)参考cloud-provider-payment8001,新建cloud-provider-payment8002

    2)改POM

    3)写YML

    4)主启动类

    5)修改8001/8002的Controller

    6、负载均衡

    问题:订单服务访问地址不能写死

    1)改写URL

    package com.atguigu.springcloud.controller;
    
    import com.atguigu.springcloud.entities.CommonResult;
    import com.atguigu.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.PostMapping;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.client.RestTemplate;
    
    import javax.annotation.Resource;
    
    @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;
    
        @PostMapping("/consumer/payment/create")
        public CommonResult<Payment> create(Payment payment) {
            return restTemplate.postForObject(PAYMENT_URL + "/payment/create", payment, CommonResult.class);  //写操作
        }
    
        @GetMapping("/consumer/payment/get/{id}")
        public CommonResult<Payment> getPayment(@PathVariable("id") Long id) {
            return restTemplate.getForObject(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);
        }
    }

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

    package com.atguigu.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;
    
    @Configuration
    public class ApplicationContextConfig {
        @Bean
        @LoadBalanced
        public RestTemplate getRestTemplate(){
            return new RestTemplate();
        }
    }

    7、测试02

    1. 先要启动EurekaServer,7001/7002服务
    2. 再要启动服务提供者provider,8001/8002服务
    3. http://localhost/consumer/payment/get/31

    结果:负载均衡效果达到,8001/8002端口交替出现。

    Ribbon 和 Eureka 整合后 Consumer 可以直接调用服务而不用再关心地址和端口号,且该服务还有负载功能了

    四、actuator微服务信息完善

    1、主机名称:服务名称修改

    2、访问信息有ip信息提示

    修改cloud-provider-payment8001配置文件

    eureka:
      client:
        register-with-eureka: true
        fetchRegistry: true
        service-url:
          #defaultZone: http://localhost:7001/eureka
          defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka  #集群版
      instance:
        instance-id: payment8001 #服务名称修改
        prefer-ip-address: true #访问信息有ip信息提示

    效果如下:

    五、服务发现Discovery

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

    1、8001主启动类@EnableDiscoveryClient

    2、修改cloud-provider-payment8001的Controller

    @Resource
    private DiscoveryClient discoveryClient;
     
    @GetMapping(value = "/payment/discovery")
    public Object discovery(){
        List<String> services = discoveryClient.getServices();
        for (String element : services) {
            log.info("***** element:"+element);
        }
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for (ServiceInstance instance : instances) {
            log.info(instance.getServiceId()+"	"+instance.getHost()+"	"+instance.getPort()+"	"+instance.getUri());
        }
        return this.discoveryClient;
    }

    控制台输出结果

    六、Eureka自我保护

    1、故障现象

    保护模式主要用于一组客户端和 Eureka Server 之间存在网络分区场景下的保护。一旦进入保护模式,Eureka Server 将会尝试保护其服务注册表中的信息,不再删除服务注册表中的数据,也就是不会注销任何微服务。如果在 Eureka Server 的首页看到以下这段提示,则说明 Eureka 进入了保护模式:

    2、导致原因

    为什么会产生 Eureka 自我保护机制?

      为了防止 Eureka Client 可以正常运行,但是与 Eureka Server 网络不通情况下,Eureka Server 不会立刻将 Eureka Client 服务剔除

    什么是自我保护模式?

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

      在自我保护模式中,Eureka Server 会保护服务注册表中的信息,不再注销任何服务实例。它的设计哲学就是宁可保留错误的服务注册信息,也不盲目注销任何可能健康的服务实例。一句话讲解:好死不如赖活着。

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

    3、怎么禁止自我保护(一般生产环境中不会禁止自我保护)

    注册中心eureakeServer端7001

    server:
      enable-self-preservation: false
      eviction-interval-timer-in-ms: 2000

    生产者客户端eureakeClient端8001

    instance:
      #Eureka 客户端向服务端发送心跳的时间间隔,单位为秒
      lease-renewal-interval-in-seconds: 1 #默认30
      #Eureka 服务端在收到最后一次心跳后等待时间上限,超时将剔除服务,单位是秒
      lease-expiration-duration-in-seconds: 2 #默认90

    4、测试

    1. 7001和8001都配置完成
    2. 先启动7001再启动8001
    3. 先关闭8001,马上被删除了
  • 相关阅读:
    CodeForces 825G"Tree Queries"(选根建树)
    技术日记
    [express.js 使用笔记] ajax询问数据,却显示在浏览器上,该怎么办?
    node.js 基础和文件操作 笔记
    JSON 笔记
    CSS 学习笔记(一)选择器
    cf1321E
    [学习笔记] 后缀数组
    Python 编程练习
    《明朝那些事儿》 读书笔记
  • 原文地址:https://www.cnblogs.com/jwen1994/p/14267188.html
Copyright © 2011-2022 走看看