Eureka服务注册发现

2,346 阅读2分钟

为什么需要注册中心 ?

image.png

进入注册中心

image.png

1.提供服务注册

2.提供服务发现

demo示意图

image.png

  • order 服务模块下单操作需要获取 product服务的数据信息
  • 用Eureka 注册发现功能

创建eureka-server搭建

image.png

Spring Cloud Discovery -> Eureka Server

添加启动注解 @EnableEurekaServer

image.png

修改properties 为 yml

server:
  port: 8761

eureka:
  instance:
    hostname: localhost
  client:
    register-with-eureka: false
    fetch-registry: false
    service-url:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
  server:
    enable-self-preservation: false

http://localhost:8761/

image.png

自我保护机制

Eureka Server 在运行期间会去统计心跳失败比例在 15 分钟之内是否低于 85%,如果低于 85%,Eureka Server 会将这些实例保护起来,让这些实例不会过期,但是在保护期内如果服务刚好这个服务提供者非正常下线了,此时服务消费者就会拿到一个无效的服务实例,此时会调用失败,对于这个问题需要服务消费者端要有一些容错机制,如重试,断路器等。

我们在单机测试的时候很容易满足心跳失败比例在 15 分钟之内低于 85%,这个时候就会触发 Eureka 的保护机制,一旦开启了保护机制,则服务注册中心维护的服务实例就不是那么准确了,此时我们可以使用eureka.server.enable-self-preservation=false来关闭保护机制,这样可以确保注册中心中不可用的实例被及时的剔除(不推荐)

server:
  enable-self-preservation: false

product-server

勾选 Eureka Discovery Client

image.png

配置yml

server:
  port: 8081
spring:
  application:
    name: product-server
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/

完善业务

返回数据是xml

通过插件看到pom.xml 里面有个包含了xml jar包 记得移除

image.png

image.png

order-server

添加ribbon

image.png

因为我的idea没有Ribbo 我得手动添加了

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>

报错 然后得添加版本哦 我觉得可能是因为 版本和springcloud版本不一致

<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
<version>2.2.9.RELEASE</version>

yml

server:
  port: 8090
spring:
  application:
    name: order-server
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/

ribbo

image.png

bug

ip注册

导致很多bug