1、微服务构建:springboot
pom.xml 基本引入(也可通过springInitlizr 时选择导入)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
这样可以配置spring的基本注解,并进行使用
启动:java -jar target/${project.build.finalname}.jar --spring.profiles.active=xxx
2、服务治理: Spring Cloud Eureka
2.1、server端
-
pom.xml
<!-- 当需要两个注册中心相互注册同步时引入-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
<version>1.4.5.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-eureka-server -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka-server</artifactId>
<version>1.4.5.RELEASE</version>
</dependency>
-
主程序(EurekaApplication)
加注解@EnableEurekaServer
@EnableEurekaServer
@SpringBootApplication
public class EurekaApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaApplication.class, args);
}
}
-
配置文件 (peer1 peer2相互注册)
application.yml
spring:
profiles:
#默认使用peer
active: peer1
application:
name: eureka-server
eureka:
server:
# 自我保护模式,当出现出现网络分区、eureka在短时间内丢失过多客户端时,会进入自我保护模式,即一个服务长时间没有发送心跳,eureka也不会将其删除,默认为true
enable-self-preservation: false
# 过期实例应该启动并运行的时间间隔,单位为毫秒,默认为60 * 1000
eviction-interval-timer-in-ms: 60000
application-peer1.yml
server:
port: 1111
eureka:
instance:
hostname: peer1
client:
#eureka服务器上注册自己
register-with-eureka: false
#不获取eureka服务器注册表上的注册信息
fetch-registry: false
#注册中心位置-相互注册
service-url:
defaultZone : http://peer2:1111/eureka/
application-peer2.yml
server:
port: 2222
eureka:
instance:
hostname: peer2
client:
#eureka服务器上注册自己
register-with-eureka: false
#不获取eureka服务器注册表上的注册信息
fetch-registry: false
#注册中心位置-相互注册
service-url:
defaultZone : http://peer1:1111/eureka/
2.2 client端
-
pom.xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
<version>1.4.5.RELEASE</version>
</dependency>
-
主程序**Application.java(如需发现服务时加,只注册不需要 例如:api-gateway)
增加@EnableDiscoveryClient
-
配置文件
application.yml
spring:
application:
name: **-service
eureka:
client:
service-url:
defaultZone: http://peer1:1111/eureka/,http://peer2:2222/eureka/
这样,client就可以通过service在Eureka注册的应用名(service自己的spring.application.name)进行调用,不需关注他的端口号
3、分布式配置中心: Spring Cloud Config&&消息总线: Spring Cloud Bus
(注:通过配置中心刷新配置文件的链接为:http://host:port/actuator/bus-refresh ;其中host、port为config-server服务的)
3.1 config-server端
-
pom.xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</ar