搭建Eureka注册中心

eureka注册中心的启动就像启动一个Spring Boot服务一样,在依赖中引用eureka的starter包:

  1. <dependency>
  2. <groupId>org.springframework.cloud</groupId>
  3. <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
  4. </dependency>

在application.yml配置文件中增加配置:

  1. server:
  2. port: 7001
  3. eureka:
  4. instance:
  5. hostname: eureka7001.com # 当前节点的名称
  6. client:
  7. fetch-registry: false # 不注册自己
  8. register-with-eureka: false # 不检索自己
  9. service-url:
  10. defaultZone: http://eureka7002.com:7002/eureka/ # 配置其它节点地址,搭建集群时使用
  11. server:
  12. # 关闭自我保护机制,保证不可用服务立即被踢出
  13. enable-self-preservation: false
  14. eviction-interval-timer-in-ms: 2000

在启动类中增加注解@EnableEurekaServer

  1. @SpringBootApplication
  2. @EnableEurekaServer
  3. public class EurekaMain7001 {
  4. public static void main(String[] args) {
  5. SpringApplication.run(EurekaMain7001.class, args);
  6. }
  7. }

启动之后通过浏览器http://localhost:7001/控制台查看:
image.png

使用Eureka注册中心

pom.xml增加依赖:

  1. <dependency>
  2. <groupId>org.springframework.cloud</groupId>
  3. <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
  4. </dependency>

在启动类上增加注解@EnableDiscoveryClient

  1. @SpringBootApplication
  2. @EnableEurekaClient
  3. @EnableDiscoveryClient
  4. public class PaymentMain8001 {
  5. public static void main(String[] args) {
  6. SpringApplication.run(PaymentMain8001.class, args);
  7. }
  8. }

application.yml配置文件中增加Eureka注册中心的配置:

  1. eureka:
  2. client:
  3. fetch-registry: true
  4. register-with-eureka: true
  5. service-url:
  6. defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka
  7. instance:
  8. ip-address: 127.0.0.1
  9. instance-id: payment8001
  10. prefer-ip-address: true
  11. # 向eureka发送心跳间隔(默认是30秒)
  12. lease-renewal-interval-in-seconds: 1
  13. # eureka收到最后一次心跳后等待时间上限,超时将剔除服务(默认是90秒)
  14. lease-expiration-duration-in-seconds: 2

这样就可以把服务注册到Eureka中了:
image.png