创建“服务注册中心”
创建一个基础的Spring Boot工程,并在pom.xml
中引入需要的依赖内容:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka-server</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Dalston.SR2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
通过@EnableEurekaServer
注解启动一个服务注册中心提供给其他应用进行对话。
/**
* @author 向振华
* @date 2018/10/23 17:00
*/
@EnableEurekaServer
@SpringBootApplication
public class Application {
public static void main(String[] args) {
new SpringApplicationBuilder(Application.class).web(true).run(args);
}
}
在默认设置下,该服务注册中心也会将自己作为客户端来尝试注册它自己,所以我们需要禁用它的客户端注册行为,只需要在application.properties
中问增加如下配置:
server.port=1001
eureka.instance.hostname=localhost
#自我保护机制
eureka.server.enable-self-preservation=true
#自动剔除下线服务间隔毫秒
eureka.server.eviction-interval-timer-in-ms=5000
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
eureka.client.serviceUrl.defaultZone=http://${eureka.instance.hostname}:${server.port}/eureka/
启动工程后,访问:http://localhost:1001/
创建“服务提供方”
下面我们创建提供服务的客户端,并向服务注册中心注册自己。
创建一个基础的Spring Boot工程,并在pom.xml
中引入需要的依赖内容:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--服务注册-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka-server</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Dalston.SR2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
在主类中通过加上@EnableDiscoveryClient
注解,该注解能激活Eureka中的DiscoveryClient
实现
/**
* @author 向振华
* @date 2018/10/23 17:00
*/
@EnableDiscoveryClient
@SpringBootApplication
public class Application {
public static void main(String[] args) {
new SpringApplicationBuilder(Application.class).web(true).run(args);
}
}
对application.properties
做一些配置工作
spring.application.name=test-server
server.port=1003
eureka.client.serviceUrl.defaultZone=http://localhost:1001/eureka/
启动工程后,访问:http://localhost:1001/
服务已经注册到eureka。