微服务之注册中心-Eureka

120 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第12天,点击查看活动详情

前言

上一篇搭建了基本的Eureka服务注册中心,今天我们要把payment注册进EurekaServer作为服务提供者 consumer作为服务调用者 image.png

源码地址

Payment服务提供

首先引入client依赖包

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

在主启动类增加注解

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

修改配置文件

eureka:
  client:
    register-with-eureka: true #是否向注册中心注册自己
    fetchRegistry: true #是否从注册中心抓取已有的注册信息 默认true,集群必须设置为true
    service-url:
      #      设置与eureka server交互的地址查询服务和注册服务都需要依赖这个地址
      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地址
#    Eureka客户端向服务端发送心跳的时间间隔,单位为秒(默认是30秒)
#    lease-renewal-interval-in-seconds: 1
#    Eureka服务端在收到最后一次心跳后等待时间上限,单位为秒(默认是90秒),超时将剔除服务
#    lease-expiration-duration-in-seconds: 2

以上的准备做完之后,我们启动Payment中心,打开Eureka网页版发现多了一个服务叫payment-service

image.png

服务名取自配置文件中设置的应用名

image.png

Comsumer服务消费

修改pom.xml,配置文件

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

主启动类同样加上注解,启动项目

image.png

可以观察看两个服务都注册上去了

总结

今天我们把payment和consumer的服务都注册到了eurake注册中心上了