推荐 Spring Boot/Cloud 视频:
示例源码
Spring Boot 2.0,Eureka和Spring Cloud Config Gateway Sleuth快速构建微服务
我的博客上有很多关于Spring Boot和Spring Cloud的微服务的文章。本文的主要目的是简要概述这些框架提供的最重要的组件,这些组件可帮助您创建微服务。本文涉及的主题是:
- 在云原生开发中使用Spring Boot 2.0
- 使用Spring Cloud Netflix Eureka为所有微服务提供服务发现
- 使用Spring Cloud Config进行分布式配置
- 使用Spring Cloud中的新项目的API网关模式:Spring Cloud Gateway
- 将日志与Spring Cloud Sleuth相关联
在我们进入源代码之前,让我们看一下下图。它说明了我们的示例系统的架构。我们有三个独立的微服务,它们在服务发现中注册自己,从配置服务中获取属性并相互通信。整个系统隐藏在API网关之后。
目前,Spring Cloud的最新版本是 Finchley.M9。此版本spring-cloud-dependencies应声明为依赖项管理的pom.xml:
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Finchley.M9</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
现在,让我们考虑采取进一步措施,以便使用Spring Cloud创建基于微服务的工作系统。我们将从Configuration Server开始。
步骤1.使用Spring Cloud Config构建配置服务器
要为应用程序启用Spring Cloud Config功能,请首先包括spring-cloud-config-server项目依赖项。
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
然后在应用程序启动期间启用运行嵌入式配置服务器的 @EnableConfigServer注解
@SpringBootApplication
@EnableConfigServer
public class ConfigApplication {
public static void main(String[] args) {
new SpringApplicationBuilder(ConfigApplication.class).run(args);
}
}
默认情况下,Spring Cloud Config Server将配置数据存储在Git存储库中。这在生产模式下是非常好的选择,但对于样本目的文件系统后端就足够了。从配置服务器开始真的很容易,因为我们可以将所有属性放在类路径中。Spring Cloud Config默认搜索以下位置内的属性源:classpath:/, classpath:/config, file:./, file:./config。
我们将所有的财产来源放在里面src/main/resources/config。YAML文件名将与服务名称相同。例如,发现服务的YAML文件将位于此处:src/main/resources/config/discovery-service.yml。
最后两件重要的事情。如果您想使用文件系统后端启动配置服务器,则可以激活Spring Boot配置文件本机。可以通过–spring.profiles.active=native在应用程序引导期间设置参数来实现。我还通过在文件中设置属性将默认配置服务器端口(8888)更改为8061。server.portbootstrap.yml
步骤2.使用Spring Cloud Netflix Eureka构建服务发现
重要的是配置服务器。现在,所有其他应用程序(包括发现服务)都需要添加spring-cloud-starter-config依赖项才能启用配置客户端。我们还必须包括依赖spring-cloud-starter-netflix-eureka-server。
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
然后,您应该在应用程序启动期间通过@EnableEurekaServer在主类上设置注解来启用运行嵌入式发现服务器。
@SpringBootApplication
@EnableEurekaServer
public class DiscoveryApplication {
public static void main(String[] args) {
new SpringApplicationBuilder(DiscoveryApplication.class).run(args);
}
}
应用程序必须从配置服务器获取属性源。客户端所需的最小配置是应用程序名称和配置服务器的连接设置。
spring:
application:
name: discovery-service
cloud:
config:
uri: http://localhost:8088
正如我已经提到的,配置文件discovery-service.yml应放在config-servic