• 【SpringCloud】Eureka服务注册与发现


    Eureka服务注册与发现

    Eureka基础知识

    什么是服务治理

    Spring Cloud封装了Netlix公司开发的Eureka模块来实现服务治理

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

    什么是服务注册与发现

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

    Eureka两组件

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

    • Eureka Server提供服务注册服务
      各个微服务节点通过配置启动后,会在EurekaServer中进行注册,这样EurekaServer中的服务注册表中将会存储所有可用服务节点的信息,服务节点的信息可以在界面中直观看到。
    • EurekaClient通过注册中心进行访问
      是一个Java客户端,用于简化Eureka Server的交互,客户端同时也具备-个内置的、 使用轮询(round-robin)负载算法的负载均衡器。在应用启动后,将会向Eureka Server发送心跳(默认周期为30秒)。 如果Eureka Server在多个心跳周期内没有接收到某个节点的心跳,EurekaServer将 会从服务注册表中把这个服务节点移除(默认90秒)

    单机Eureka构建步骤

    IDEA生成EurekaServer端服务注册中心# 类似物业公司

    建Module

    cloud-eureka-server7001

    改POM

    <dependencies>
        <!--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-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.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>

    1.x和2.x的对比说明

    写YML

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

    主启动

    @EnableEurekaServer

    @SpringBootApplication
    @EnableEurekaServer
    public class EurekaMain7001 {
    
        public static void main(String[] args) {
            SpringApplication.run(EurekaMain7001.class,args);
        }
    }

    测试

    http://localhost:7001/

    结果页面


    No application available没有服务被发现
    因为没有注册服务进来当前不可能有服务被发现

    EurekaClient端cloud-provider-payment8001 将注册进EurekaServer成为服务提供者provider,类似于尚硅谷学校对外提供授课服务

    建Module

    cloud-provider-payment8001

    改POM

    新增该eureka-client组件

    <!--eureka client-->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>

    写YML

    新增

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

    主启动

    @EnableEurekaClient

    @SpringBootApplication
    @EnableEurekaClient
    public class PaymentMain8001 {
    
        public static void main(String[] args) {
            SpringApplication.run(PaymentMain8001.class,args);
        }
    }

    测试

    先要启动EurekaServer

    http://localhost:7001/

    微服务注册名配置说明

    自我保护机制

    EurekaClient端cloud-consumer-order80 将注册进EurekaServer成为服务消费者consumer,类似于尚硅谷学校上课消费的各位同学

    建Module

    cloud-consumer-order80

    改POM

    <!--eureka client-->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>

    写YML

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

    主启动

    @EnableEurekaClient

    @SpringBootApplication
    @EnableEurekaClient
    public class OrderMain80 {
    
        public static void main(String[] args) {
            SpringApplication.run(OrderMain80.class,args);
        }
    }

    测试

    先要启动EurekaServer 7001服务

    再启动服务提供者provider 8001服务

    eureka服务器

    http://localhost/consumer/payment/get/31

    bug

    failed to bind properties under 'eureka.client.service-url' to java.util.Map

    集群Eureka构建步骤

    Eureka集群原理说明


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

    Eureka集群环境构建步骤

    参考cloud-eureka-server7001

    新建cloud-eureka-server7002

    改POM

    修改映射配置

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

    修改映射配置添加hosts文件

    127.0.0.1 eureka7001.com
    127.0.0.1 eureka7002.com

    修改原因:主机名一个名字(127.0.0.1)还能叫集群吗。

    刷新hosts文件

    ipconfig /flushdns

    写YMl(以前单机)

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

    7001

    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://${eureka.instance.hostname}:${server.port}/eureka/
          # 相互注册
          defaultZone: http://eureka7002.com:7002/eureka/

    7002

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

    主启动

    将支付服务8001微服务发布到上面2台Eureka集群配置中

    YAML

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

    将订单服务80微服务发布到上面2台Eureka集群配置中

    YML,一样的修改

    测试01

    先要启动EurekaServer,7001/7002服务

    再要启动服务提供者provider,8001

    再要启动消费者,80

    http://localhost/consumer/payment/get/31

    支付服务提供者8001集群环境搭建

    参考cloud-provider-payment8001

    新建cloud-provider-payment8002

    改POM

    YAML

    server:
      port: 8002
    spring:
      application:
        name: cloud-payment-service8002
      datasource:
        # 当前数据源操作类型
        type: com.alibaba.druid.pool.DruidDataSource
        # mysql驱动类
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://localhost:3306/db2019?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT%2B8
        username: root
        password: root
    eureka:
      client:
        register-with-eureka: true
        fetch-registry: true
        service-url:
          defaultZone: http://eureka7001.com/eureka,http://eureka7002.com/eureka
    mybatis:
      mapper-locations: classpath*:mapper/*.xml
      type-aliases-package: com.atguigu.springcloud.entities

    主启动

    业务类

    直接从8001粘

    修改8001/8002的controller

    8001

    @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: " + 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: " + serverPort,payment);
            } else {
                return new CommonResult(444,"没有对应记录,查询ID: " + id,null);
            }
        }
    }

    8002

    主要是在log.info中打印端口号,验证负载均衡

    取消IDEA中重复代码提示

    File -> Setting -> Inspections -> General -> Duplicated Code 设置为不打勾√即可。

    负载均衡

    bug

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

    使用服务名访问http://CLOUD-PAYMENT-SERVICE

    public class OrderController {
    
    //    public static final String PAYMENT_URL = "http://localhost:8001";
       public static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";

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

    ApplicationContextBean

    @Configuration
    public class ApplicationContextConfig {
    
        @Bean
        @LoadBalanced
        public RestTemplate getRestTemplate() {
            return  new RestTemplate();
        }
    }

    测试02

    先要启动EurekaServer,7001/7002服务

    再要启动服务提供者provider,8001/8002服务

    http://localhost/consumer/payment/get/31

    结果

    • 负载均衡效果达到
    • 8001/8002端口交替出现

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

    actuator微服务信息完善

    主机名称:服务名称修改

    当前问题

    修改cloud-provoder-payment8001

    yaml

    效果


    访问信息有IP信息提示

    当前问题

    没有IP提示

    修改cloud-provoder-payment8001

    YAML

    效果图

    服务发现Discovery

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

    修改cloud-provider-payment8001的Controller

    @Resource
    private DiscoveryClient discoveryClient;
     
    @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()+"	" + instance.getHost() +
                    "	" + instance.getPort() +"	" + instance.getUri());
        }
    
        return  this.discoveryClient;
    }

    8001的启动类

    @EnableDiscoveryClient

    自测

    先要启动EurekaServer

    再启动8001主启动类,需要稍等一会

    http://localhost:8001/payment/discovery

    效果图

    eureka自我保护

    故障现象

    概述
    保护模式主要用于一组客户端和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.

    导致原因

    为什么会产生Eureka自我保护机制?
    为了防止EurekaClient可以正常运行,但是与EurekaServer网络不通情况下,EurekaServer不会立刻将EurekaClient服务剔除

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

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

    属于CAP里面的AP分支

    怎么禁止自我保护

    注册中心eurekaServer端7001

    出产默认,自我保护机制是开启的

    eureka.server.enable-self-preservation=true

    使用eureka.server.enable-self-preservation=false 可以禁用自我保护模式

    关闭效果

    在eurekaServer端7001处设置关闭自我保护机制

    生产者客户端eurekaClient端8001

    默认

    eureka.instance.lease-renewal-interval-in-seconds=30

    Eureka客户端向服务端发送心跳的时间间隔,单位为秒(默认是30秒)

    eureka.instance.lease-expiration-duration-in-seconds=90

    Eureka服务端在收到最后一次心跳后等待时间上限 ,单位为秒(默认是90秒),超时剔除服务

    配置

    Eureka服务端
    eureka:
       server:
         #关闭自我保护模式,保证不可用服务被及时删除
         enable-self-preservation: false
         eviction-interval-timer-in-ms: 2000
     
     
    服务消费者 Payment
    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/
          #单机版
          defaultZone: http://eureka7001.com:7001/eureka/
      instance:
        instance-id: payment8001
        prefer-ip-address: true #访问路径可以显示ip
        #Eureka客户端向服务端发送心跳的实际间隔,单位为秒(默认为30秒)
        lease-renewal-interval-in-seconds: 1
        #Eureka服务端收到最后一次心跳后等待时间上线,单位为秒(默认为90秒) 超时将剔除服务
        lease-expiration-duration-in-seconds: 2

    测试

    7001和8001都配置成功

    先启动7001再启动8001

    先关闭8001


    马上被删除了

    后海有树的院子,夏代有工的玉,此时此刻的云,二十来岁的你。——《可遇不可求的事》

    笔者将不定期更新【考研或就业】的专业相关知识以及自身理解,希望大家能【关注】我。
    如果觉得对您有用,请点击左下角的【点赞】按钮,给我一些鼓励,谢谢!
    如果有更好的理解或建议,请在【评论】中写出,我会及时修改,谢谢啦!
    关注
    评论
    收藏
    Top
  • 相关阅读:
    电工知识:3种方法测电容的好坏,万用表三个档位的巧妙应用
    ps 教程
    绘声绘影 设置不联网
    推荐.Net、C# 逆向反编译四大工具利器
    MOOC 网站:Coursera、Udacity、edX
    深度强化学习资料(视频+PPT+PDF下载)
    李飞飞、吴恩达、Bengio等人的15大顶级深度学习课程
    tf.name_scope()和tf.variable_scope()
    Linux 进程(一):环境及其控制
    Linux I/O总结
  • 原文地址:https://www.cnblogs.com/blknemo/p/13526455.html
Copyright © 2020-2023  润新知