在Spring Cloud实现一个Eureka Server是一件非常简单的事情。下面我们来写一个Eureka Server DEMO。
编码
(1) 首先创建一个Maven工程,添加内容如下:
"1.0" encoding="UTF-8"
xml version=
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0
</modelVersion>
<groupId>com
.itmuch
.cloud
</groupId>
<artifactId>microservice-discovery-eureka
</artifactId>
<version>0.0.1-SNAPSHOT
</version>
<packaging>jar
</packaging>
<!-- 引入spring boot的依赖 -->
<parent>
<groupId>org
.springframework
.boot
</groupId>
<artifactId>spring-boot-starter-parent
</artifactId>
<version>1.4.1.RELEASE
</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-
8
</project.build.sourceEncoding>
<java.version>1.8
</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org
.springframework
.cloud
</groupId>
<artifactId>spring-cloud-starter-eureka-server
</artifactId>
</dependency>
</dependencies>
<!-- 引入spring cloud的依赖 -->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org
.springframework
.cloud
</groupId>
<artifactId>spring-cloud-dependencies
</artifactId>
<version>Camden.SR1
</version>
<type>
pom
</type>
<scope>import
</scope>
</dependency>
</dependencies>
</dependencyManagement>
<!-- 添加spring-boot的maven插件 -->
<build>
<plugins>
<plugin>
<groupId>org
.springframework
.boot
</groupId>
<artifactId>spring-boot-maven-plugin
</artifactId>
</plugin>
</plugins>
</build>
</project>
|
(2) 编写启动类,在启动类上添加@EnableEurekaServer
注解。
public
class EurekaApplication
{
public static void main(String[] args) {
SpringApplication
.run(
EurekaApplication
.class,
args);
}
}
|
(3) 编写配置文件application.yml
server:
port:
8761
eureka:
client:
registerWithEureka:
false
fetchRegistry:
false
serviceUrl:
defaultZone:
http://localhost:8761/eureka/
|
这样就完成了一个简单的Eureka Server。简要说明一下application.yml中的配置项:
eureka.client.registerWithEureka
:表示是否将自己注册到Eureka Server,默认为true。由于当前这个应用就是Eureka Server,故而设为false。eureka.client.fetchRegistry
:表示是否从Eureka Server获取注册信息,默认为true。因为这是一个单点的Eureka Server,不需要同步其他的Eureka Server节点的数据,故而设为false。eureka.client.serviceUrl.defaultZone
:设置与Eureka Server交互的地址,查询服务和注册服务都需要依赖这个地址。默认是http://localhost:8761/eureka
;多个地址可使用 , 分隔。
Eureka的配置类所在类:
org
.springframework
.cloud
.netflix
.eureka
.EurekaInstanceConfigBean
org
.springframework
.cloud
.netflix
.eureka
.EurekaClientConfigBean
org
.springframework
.cloud
.netflix
.eureka
.server
.EurekaServerConfigBean
|
测试
启动工程后,访问:http://localhost:8761/ 。我们会发现此时还没有服务注册到Eureka上面,如下图:
该页面展示了Eureka的系统状态、当前注册到Eureka Server上的服务实例、一般信息、实例信息等。我们可以看到,当前还没有任何服务被注册到Eureka Server上。