废话不多说,直接上代码。
单节点Eureka Server
- 配置pom文件
<?xml version="1.0" encoding="UTF-8"?>
<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.example</groupId>
<artifactId>eureka</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>eureka</name>
<description>这是一个注册中心</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<spring-cloud.version>Dalston.SR1</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
- 配置配置文件
server:
#端口号
port: 8761
eureka:
instance:
hostname: localhost
client:
#注册中心 false代表不向注册中心注册自己(默认为true)
registerWithEureka: false
#表示是否从 Eureka Server 获取注册信息,默认为true。因为这是一个单点的,
#不需要同步同步其它的Eureka Server节点的数据,设置false
fetchRegistry: false
serviceUrl:
defaultZone: http://${eureka.instance.hostname}:8761/eureka/
- 启动类
在原有的里面加上@EnableEurekaServer
@EnableEurekaServer
@SpringBootApplication
public class EurekaApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaApplication.class, args);
}
}
- 测试
在浏览器输入http://localhost:8761/
测试成功!!!
服务注册到Eureka
- 在普通服务启动类加上:@EnableDiscoveryClient
@EnableDiscoveryClient
@SpringBootApplication
public class Hell0ServiceApplication {
public static void main(String[] args) {
SpringApplication.run(Hell0ServiceApplication.class, args);
}
}
- 在配置文件:
#服务命名(用于指定注册到Eureka Server上的应用名称)
spring:
application:
name: hello-service
##eureka配置
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
#表示将自己的ip注册到Eureka Server(如不配置该属性或者设置false,则表示微服务所在操作系统的name到Eureka Server)
instance:
prefer-ip-address: true
- 刷新之前Eureka