1. 概述
本文实现了包含spring cloud的所有的基本要素的完整demo。配置中心、服务注册和发现中心、通过eureka实现服务的注册和发现、通过feign+hystrix调用服务。
1.1 Demo概述
下图
配置中心:通过git/svn/本地中获取公共配置文件,并通过REST方式供其它服务获取配置信息
服务注册中心:提供服务注册和发现
服务群(服务提供者):提供服务。服务启动时,从配置中心获取公共配置信息,并将本服务通过eureka注册到注册中心。在注册时,需要配置本服务的名称,调用者通过此名称调用此服务
客户端(服务调用者):客户端启动时,从配置中心获取公共配置信息,通过要访问的服务注册到服务注册中心的名称调用对应的服务。如果服务注册的方式是eureka,则客户端也需要使用eureka访问。通过ribbon可以实现对服务群的均衡负载。hystrix作为断路器。feign方式简化了服务的调用方式。
服务路由:通过zuul实现服务的路由。 zuul的作用类似Nginx,这个模块在spring cloud不是必须的。
下文介绍如何通过spring cloud实现如上的一个简单的demo,不含zuul部分。
3. 父工程
工程:cloud-parent
在pom.xml中定义所有服务的公共依赖jar
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<!-- 使用spring cloud必须引入 -->
<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>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- logback + slf4j -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
</dependency>
<!-- 测试模块,包括JUnit、Hamcrest、Mockito -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.37</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>
spring-boot-configuration-processor
</artifactId>
</dependency>
</dependencies>
3. 配置中心
工程名称: cloud-config-center
配置中心的配置文件方式有git,本地文件(native),svn,这里只演示前2者的使用方式。
3.1. 配置文件使用git方式
工程名称: cloud-config-center
application.properties
server.port=8888
application-gitsimple.properties
# 指定配置文件所在的git工程路径
spring.cloud.config.server.git.uri=https://github.com/hryou0922/spring_cloud.git
# 表示将搜索该文件夹下的配置文件
spring.cloud.config.server.git.searchPaths=cloud-config-git/simple
CloudGitConfigServerApplication
- @EnableConfigServer :激活该应用为配置文件服务器:读取远程配置文件,转换为rest接口服务
@SpringBootApplication
@EnableConfigServer // 激活该应用为配置文件服务器:读取远程配置文件,转换为rest接口服务
public class CloudGitConfigServerApplication {
public static void main(String[] args) {
args = new String[1];
args[0] = "--spring.profiles.active=gitsimple";