1.创建一个maven父工程microservice-springcloud,并在工程的pom.xml中添加spring cloud的版本依赖信息。
<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>
2.搭建服务端工程
在父工程microservice-springcloud中,创建Maven子模块microservice-eureka-server作为服务端工程,该模块是一个基础的spring boot工程。
<1>添加依赖
<2>编写配置文件
<3>修改客户端java代码
详细:
<1>添加依赖。pom.xml中
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
<2>编写配置文件。在配置文件中增加端口号等配置信息。
spring:
port:8761
eureka:
instance:
hostname:localhost
client:
registerWithEureka: false
fetchRegistry: false
serviceUrl:
defaultZone: http://registry:8761/eureka/
上述代码中,首先配置了端口号为8761,所有服务的实例都需要向此端口注册。接下来配置了实例名为localhost。由于本项目是一个注册中心,是不需要向自己注册和检索服务的,所以 registerWithEureka和 fetchRegistry都需要设置为false。最后defaultZone中的地址是注册中心的地址。
<3>修改服务端java代码。在项目的引导类上添加注解@EnableEurekaServer,该注解用于标注类是一个Eureka Server。
@SpringBootApplication
@EnableEurekaServer
public class RegistryApplication {
public static void main(String[] args) {
SpringApplication.run(RegistryApplication.class, args);
}
}
<4>启动应用,查看信息。完成上述配置后,启动应用程序并在浏览器中访问地址http://localhost:8761,即可看到Eureka的信息面板。
3.搭建客户端工程
在父工程中创建maven子模块microservice-eureka-user作为客户端工程,该模块也是一个基础的spring boot工程。
<1>添加依赖
<2>编写配置文件
<3>修改客户端java代码
详细:
<1>添加依赖。pom.xml中
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<2>编写配置文件
server:
port:8000 #指定该Eureka实例的端口号
eureka:
instance:
prefe-ip-address:true #是否显示主机的IP
client:
registerWithEureka: false
fetchRegistry: false
serviceUrl:
defaultZone: http://registry:8761/eureka/ #指定Eureka服务端地址
spring:
application:
name:microservice-eureka-user #模块的名称
<3>修改客户端java代码
@SpringBootApplication
@EnableEurekaClient
@RestController
public class AccountApplication {
@RequestMapping("/hello")
public String home(){
return "hello world";
}
public static void main(String[] args) {
SpringApplication.run(AccountApplication.class, args);
}
}
<4>启动应用。服务会注册到应用中心,注册后的服务就可以直接被其他服务调用。