有Springboot作为基础,搭建一个SpringCloud环境非常简单。以SpringCloud的注册中心Eureka为例,搭建一个SpringCloud父子工程。
工程。
1、整体的框架接口如下图所示:
2、IDEA建立工程具体步骤如下
建立父工程:
①IDEA中新建一个工程:New Project,Choose Initializr Service URL选择Default。
②首先建立父工程,填写好Group和Atrifact(字母小写即可,大写会报错),Type选择Maven POM,其他可以默认即可。
③由于建立父工程,该步骤不选任何选项,默认即可。
④根据自己的实际情况选择相应的文件目录。
⑤完成后的基本结构如下:
⑥父工程pom.xml文件:
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.1.6.RELEASE
com.aaron
springcloudeureka
0.0.1-SNAPSHOT
springcloudeureka
Demo projec
1.8
Greenwich.SR2
eurekaservice
eurekaclient
org.springframework.boot
spring-boot-starter
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
test
org.springframework.cloud
spring-cloud-dependencies
${spring-cloud.version}
pom
import
org.springframework.boot
spring-boot-maven-plugin
建立注册中心服务器端EurekaService子工程:
①选择父工程,选择新建New,再选择Module。
②Choose Initializr Service URL选择Default。
③填写好Group和Atrifact(字母小写即可,大写会报错),Type选择Maven Project,其他可以默认即可。
④由于该Module搭建eureka注册中心,所以需要选择Spring Cloud Discovery的Eureka Server选项。
⑤Module name命名自己定义即可,Content root和Module file location选择在父工程目录下建立即可。一般默认,也可以自定义名称。
⑥完成后的基本结构如下:
⑦修改子工程EurekaService的pom.xml文件,让它继承父工程中的pom.xml文件,公共的pom可以从父工程的pom中继承过来即可。
4.0.0
com.aaron
eurekaservice
0.0.1-SNAPSHOT
eurekaservice
Demo project for Spring Boot
jar
com.aaron
springcloudeureka
0.0.1-SNAPSHOT
org.springframework.cloud
spring-cloud-starter-netflix-eureka-server
⑧配置注册中心yml文件
server:
port: 9000
#name不能够使用下划线,即:Eureka_Service
spring:
application:
name: Eureka-Service
eureka:
instance:
hostname: 127.0.0.1
client:
register-with-eureka: false
fetch-registry: false
service-url:
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
⑨添加注解@EnableEurekaServer到启动类。
@SpringBootApplication
@EnableEurekaServer
public class EurekaserviceApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaserviceApplication.class, args);
}
}
建立注册中心客户端EurekaClient子工程:
建立步骤类似建立EurekaService注册中心,不同点如下:
①选择Spring Cloud Discovery选择Eureka Discovery Client
②子工程EurekaClient的pom.xml文件:
4.0.0
com.aaron
eurekaclient
0.0.1-SNAPSHOT
eurekaclient
Demo project for Spring Boot
jar
com.aaron
springcloudeureka
0.0.1-SNAPSHOT
org.springframework.cloud
spring-cloud-starter-netflix-eureka-client
③配置注册中心yml文件
server:
port: 3001
spring:
application:
#name不能够使用下划线,即:Member_Service
name: Eureka-Client
eureka:
client:
service-url:
defaultZone: http://localhost:3000/eureka
register-with-eureka: true
fetch-registry: true
④添加注解@EnableEurekaClient到启动类。
@SpringBootApplication
@EnableEurekaClient
public class EurekaclientApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaclientApplication.class, args);
}
}
3、启动EurekaService和EurekaClient,并访问localhost:3000即可。