《SpringCloud超级入门》使用Eureka编写注册中心服务《九》

426 阅读2分钟

这是我参与 8 月更文挑战的第 16天,活动详情查看: 8月更文挑战

Eureka介绍

Spring Cloud Eureka 是 Spring Cloud Netflix 微服务套件的一部分,基于 Netflix Eureka 做了二次封装,主要负责完成微服务架构中的服务治理功能。

除了用Eureka来做注册中心,还可以使用Consul、Etcd、Zookeeper等等来作为服务的注册中心。

有用过dubbo的同学应该清楚,dubbo中也有几种注册中心,有基于Zookeeper的,有基于redis的等等,用的最多的还是Zookeeper方式。

至于使用哪种方式,其实都是可以的,注册中心无非就是管理所有服务的信息和状态。

首先创建一个 Maven项目,取名为 eureka-server,在 pom.xml 中配置 Eureka 的依赖信息。

<!-- Spring Boot -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.6.RELEASE</version>
<relativePath />
</parent>

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

<!-- Spring Cloud -->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Finchley.SR2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

创建一个启动类 EurekaServerApplication,代码如下所示。

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

这里的启动类,就是和 Spring Boot 几乎完全一样,只是多了一个 @EnableEurekaServer 注解,表示开启 Eureka Server。

接下来在 src/main/resources 下面创建一个 application.properties 属性文件,增加下面的配置:

spring.application.name=eureka-server
server.port=8761
# 由于该应用为注册中心, 所以设置为false, 代表不向注册中心注册自己
eureka.client.register-with-eureka=false
# 由于注册中心的职责就是维护服务实例, 它并不需要去检索服务, 所以也设置为 false
eureka.client.fetch-registry=false

eureka.client.register-with-eureka 一定要配置为 false,不然启动时会把自己当作客户端向自己注册,会报错。

接下来直接运行 EurekaServerApplication 就可以启动我们的注册中心服务了。我们在 application.properties 配置的端口是 8761,则可以直接通过 http://localhost:8761/ (http://localhost%EF%BC%9A8761/) 去浏览器中访问,然后便会看到 Eureka 提供的 Web 控制台。