微服务学习(三)构建一个简单的Eureka服务

一 、构建Eureka服务器

核心依赖:

<dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-eureka-server</artifactId>
</dependency>

Eureka在application.yml中的配置:

server:
  port: 8761 #Eureka监听的端口

eureka:
  client:
    registerWithEureka: false #不使用Eureka服务进行注册
    fetchRegistry: false #不在本地缓存注册表信息
  server:
    waitTimeInMsWhenSyncEmpty: 5 #服务器接收请求之前等待的时间
  serviceUrl:
    defaultZone: http://localhost:8761
  

registerWithEureka设置为false是因为当前服务为Eureka服务器,自己不需要注册自己.

启动类:

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

使用注解@EnableEurekaServer,可以让当前服务变为一个Eureka服务.

检验:

在启动服务后,能够通过http://localhost:8761访问到Eureka服务即可.

二 、新建服务,通过Eureka进行注册

核心依赖:

<dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-eureka-server</artifactId>
</dependency>

需要进行与Eureka服务器通信的服务

在application.yml中的配置:

eureka:
  instance:
    preferIpAddress: true #注册服务器的IP,不注册服务器的名称
  client:
    registerWithEureka: true #向Eureka注册服务
    fetchRegistry: true #拉取注册表的本地副本
    serviceUrl:
        defaultZone: http://localhost:8761/eureka/     #Eureka服务的位置
  

关于注册服务器IP而不是名称,有这样的解释(自己没有试验过):
在服务器中,会提供域名映射,所以一个服务器会分配一个DNS支持的主机名,这种情况下没问题.

在bootstrap.yml中的配置:

spring:
  application:
    name: organizationservice #注册的服务的名称
  profiles:
    active:
      default
  cloud:
    config:
      enabled: true

关于eureka.client.fetchRegistry,拉取注册表的本地副本.属性为true的时候,表示会在本地缓存注册表.这样的话,不需要每次查找服务都去调用Eureka服务去查询.在间隔一段时间后,会重新联系Eureka服务,更新注册表.

验证:

启动服务后,稍等一段时间后,访问http://localhost:8761/eureka,可以看到被注册的organizationservice服务.

关于健康检查

服务通过Eureka进行注册后,不能够立刻访问.Eureka会在30s内进行3次健康检查.检查完毕后,才能够通过Eureka获取该服务.

posted @ 2021-04-30 17:55  Monstro  阅读(107)  评论(0)    收藏  举报