今天继续学习SpringCloud。
上篇我们讲了[Feign和Hystrix]
这一篇针对配置中心和服务跟踪详细说说
以下代码皆用最简单的代码示例,并非真正的业务代码
学习中用到的学习资料如下:
配置中心
在基于微服务的分布式系统中,存在一个问题,多个微服务所对应的配置项也会非常多,一旦某个微服务进行了修改,则其他服务也需要作出调整,直接在每个微服务中修改对应的配置项是非常麻烦的,改完之后还需要重新部署项目。
Spring Cloud 提供了对应的解决方案,即 SpringCloud Config,通过服务端可以为多个客户端提供配置服务。
Spring Cloud Config 可以将配置文件存放在本地,也可以存放在远程 Git 仓库中。拿远程 Git 仓库来说,具体的操作思路是将所有的外部配置文件集中放置在 Git 仓库中,然后创建 Config Server,通过它来管理所有的配置文件,需要更改某个微服务的配置信息时,只需要在本地进行修改,然后推送到远程 Git 仓库即可,所有的微服务实例都可以通过 Config Server 来读取对应的配置信息。
本地文件系统实现
- 创建 Maven 工程,pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
<version>2.0.2.RELEASE</version>
</dependency>
</dependencies>
- 创建 application.yml
server:
port: 8762
spring:
application:
name: nativeconfigserver
profiles:
active: native
cloud:
config:
server:
native:
search-locations: classpath:/shared
注解说明
profiles.active
:配置文件的获取方式
cloud.config.server.native.search-locations
:本地配置文件存放的路径
- resources 路径下创建 shared 文件夹,并在此路径下创建 configclient-dev.yml。
server:
port: 8070
foo: foo version 1
- 创建启动类
package com.janeroad;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.config.server.EnableConfigServer;
@SpringBootApplication
@EnableConfigServer
public class NativeConfigServerApplication {
public static void main(String[] args) {
SpringApplication.run(NativeConfigServerApplication.class,args);
}
}
注解说明
@EnableConfigServer
:声明配置中心。
**创建客户端读取本地配置中心的配置文件 **
- 创建 Maven 工程,pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
<version>2.0.2.RELEASE</version>
</dependency>
</dependencies>
- 创建 bootstrap.yml,配置读取本地配置中心的相关信息。
spring:
application:
name: configclient
profiles:
active: dev
cloud:
config:
uri: http://localhost:8762
fail-fast: true
注解说明
cloud.config.uri
:本地 Config Server 的访问路径
cloud.config.fail-fase
:设置客户端优先判断 Config Server 获取是否正常。
通过 spring.application.name
结合 spring.profiles.active
拼接目标配置文件名,configclient-dev.yml,去 Config Server 中查找该文件。
- 创建启动类
package