SpringCloud学习笔记【初级篇】Eureka 服务注册与发现

一、Eureka基础知识

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

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

2. 什么是服务注册与发现(通俗版)
简单讲就是微服务框架的服务注册中心,通过服务注册中心进行双向绑定每个(客户端、子类)服务,并维持心跳连接;
系统的维护人员就可以通过Eureka Server来监控系统中各个微服务是否正常运行。

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

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

二、单机Eureka构建步骤

消费者端口80,提供者端口8001,Eureka端口7001
1.Server模块
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">
    <parent>
        <artifactId>cloud2020</artifactId>
        <groupId>springcloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
 
    <artifactId>cloud-eureka-server7001</artifactId>
 
    <dependencies>
        <!--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>
        <dependency>
            <groupId>springcloud</groupId>
            <artifactId>cloud-api-commons</artifactId>
            <version>${project.version}</version>
        </dependency>
    </dependencies>
</project>

jar包版本说明:

<!--SpringBoot2.X-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
 
 
<!--SpringBoot1.X-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>

application.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://localhost:7001/eureka/

测试: http://localhost:7001

2.8001注册进Eureka成为提供者
pom.xml

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

application.yml

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

主启动类

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

测试: http://localhost:7001 能在Status列下看到8001节点

3、80注册进Eureka成为消费者
pom.xml

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

application.yml

eureka:
  client:
    register-with-eureka: true
    fetch-registry: true
    service-url:
      defaultZone: http://localhost:7001/eureka/

主启动类

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

测试: http://localhost:7001 能在Status列下看到80节点

三、集群Eureka构建步骤

1、集群原理说明
在这里插入图片描述
问题:微服务RPC远程服务调用最核心的是什么?

高可用,试想你的注册中心只有一个only one, 它出故障了那就呵呵( ̄▽ ̄)"了,会导致整个为服务环境不可用,所以解决办法:搭建Eureka注册中心集群 ,实现负载均衡+故障容错
2、集群环境构建
参考cloud-eureka-server7001,新建cloud-eureka-server7002

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

127.0.0.1 eureka7001.com
127.0.0.1 eureka7002.com

  • 注册服务端会报如下错误

Connect to eureka7001.com:7001 timed out

application.yml
与单机版不同的是,defaultZone指向了其他注册中心的地址

7001:

server:
 port: 7001
 
eureka:
 instance:
   hostname: eureka7001.com  # eureka 服务端的实例名称
 
 client:
   # false 代表不向服务注册中心注册自己,因为它本身就是服务中心
   register-with-eureka: false
   # false 代表自己就是服务注册中心,自己的作用就是维护服务实例,并不需要去检索服务
   fetch-registry: false
   service-url:
     # 设置与 Eureka Server 交互的地址,查询服务 和 注册服务都依赖这个地址
     #集群指向其他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 交互的地址,查询服务 和 注册服务都依赖这个地址
      # 集群指向其他eureka
      defaultZone: http://eureka7001.com:7001/eureka/

测试: http://localhost:7001 能在DS Replicas看到7002;http://localhost:7002 能在DS Replicas看到7001

3、8001发布到2台Eureka集群

  • 集群版
defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/
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/,http://eureka7002.com:7002/eureka/
mybatis:
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.atguigu.springcloud.entities  # 所有Entity 别名类所在包

4、80发布到2台Eureka集群

  • 集群版
defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/
server:
  port: 80
 
spring:
  application:
    name: cloud-order-service
eureka:
  client:
    register-with-eureka: true
    fetch-registry: true
    service-url:
      # 提供者注册到多个eureka中
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/

测试: 先要启动EurekaServer,7001/7002服务,再要启动服务提供者provide8001,最后再启动消费者80

6、支付服务提供者8001集群环境构建
参考cloud-provider-payment8001新建cloud-provider-payment8002

  • application.yml,只有端口号不同

server:
port: 8002

  • 修改8001/8002的PaymentServiceImpl
public class PaymentController {
    @Resource
    private PaymentService paymentService;
 
    @Value("${server.port}") //读取yml中的值
    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+"\t"+"oo哈哈");
 
        if (payment!=null){
            return new CommonResult(200,"查询成功,serverPort:"+serverPort,payment);
        }else {
            return new CommonResult(444,"查询失败",null);
        }
    }
}

7、消费者80
此时消费者一旦消费完之后,他以后访问的还是那台提供者。明显不对,原因在于消费者并没有去Eureka里找服务,而是自己找的

就是消费者如何访问 由这两个提供者组成的集群?
修改OrderController,将远程调用的地址,改成提供者在Eureka 上的名称,无需写端口号

@Slf4j
@RestController
public class OrderController {
    //远程调用的地址,改成提供者在Eureka 上的名称,无需写端口号
    public static final String PAYMENT_URL="http://cloud-payment-service";
 
    @Resource
    private RestTemplate restTemplate;
 
    @PostMapping("/consumer/payment/create")
    public CommonResult<Payment> create(@RequestBody Payment payment){
        return restTemplate.postForObject(PAYMENT_URL+"/payment/create",//请求地址
                                                payment,//请求参数
                                                CommonResult.class);//返回类型
    }
 
    @GetMapping("/consumer/payment/get/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable("id")Long id){
        return restTemplate.getForObject(PAYMENT_URL+"/payment/get/"+id,//请求地址
                                            CommonResult.class);//返回类型
    }
}

在这里插入图片描述
@LoadBalanced

开启负载均衡,CLOUD-PAYMENT-SERVICE有多个,如果不开启,不知道是哪一个,调用者不知道要调用集群下哪个服务,会报这个错误
ERROR:java.net.UnknownHostException:

  • 修改注入RestTemplate的配置类
@Configuration
public class ApplicationContextConfig {
    @Bean
    @LoadBalanced
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }
}

这时候,消费者消费的提供者多次访问就会变化了(这就是Ribbon的负载平衡功能)【即提供者会在8001和8002来回变动】
Ribbon和Eureka整合后Consumer可以直接调用服务而不用再关心地址和端口号,且该服务还有负载功能了。O(∩_∩)O

四、actuator微服务信息完善

1、当前问题

  • (1)含有主机名称
    在这里插入图片描述

  • 修改8001和8002 yml文件

8001同理

   instance:
     instance-id: payment8002 # 每个提供者的id不同,显示的不再是默认的项目名
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/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 交互的地址
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/
  instance:
    instance-id: payment8002 # 每个提供者的id不同,显示的不再是默认的项目名
mybatis:
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.atguigu.springcloud.entities  # 所有Entity 别名类所在包

测试:
在这里插入图片描述

(2)访问信息没有IP信息提示
在这里插入图片描述

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

修改8001和8002 YAML文件

prefer-ip-address: true # 可以显示ip地址
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/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 交互的地址
      #defaultZone: http://eureka7001.com:7001/eureka/
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/
  instance:
    instance-id: payment8002 # 每个提供者的id不同,显示的不再是默认的项目名
    prefer-ip-address: true # 可以显示ip地址
 
mybatis:
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.atguigu.springcloud.entities  # 所有Entity 别名类所在包

测试
在这里插入图片描述

五、服务发现Discovery

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

1、修改8001和8002的Controller

public class PaymentController {
    @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()+"\t"+instance.getHost()+"\t"+instance.getPort()+"\t"+instance.getUri());
        }
        return this.discoveryClient;
    }
}

2、主启动类

  • 主启动类添加注解:@EnableDiscoveryClient
@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient //服务发现
public class PaymentMain8002 {
    public static void main(String[] args) {
        SpringApplication.run(PaymentMain8002.class,args);
    }
}

测试
在这里插入图片描述

六、Eureka自我保护

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 

2、故障原因

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

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

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

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

属于CAP里面的AP分支

3、怎么禁止自我保护
现在可以不用集群版了,只用开一个。

注册中心eureakeServer端7001

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

 server:
   # 关闭自我保护机制,保证不可用该服务被及时剔除
   enable-self-preservation: false
   eviction-interval-timer-in-ms: 2000
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

# Eureka客户端像服务端发送心跳的时间间隔,单位s,默认30s
least-renewal-interval-in-seconds: 1
# Rureka服务端在收到最后一次心跳后等待时间上线,单位为s,默认90s,超时将剔除服务
least-expiration-duration-in-seconds: 2
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后停更了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值