在微服务架构中, 全局配置的重要性不言而喻. SpringCloud 的全局配置存储主要基于 Git 来实现, 即配置信息存储在 Git 服务器, 以统一的方式对外提供访问. 在使用上分为 ConfigServer 和 ConfigClient 这两个角色.
一. ConfigServer 的应用, 这也是一个基于 SpringBoot 和web 应用. 启动后做为配置服务器对外提供访问.
1. application.properties 文件配置
- server.port=8888
- spring.cloud.config.server.Git.uri=https://gitee.com/xxxx/config-repo
spring.cloud.config.server.Git.username={帐号}
spring.cloud.config.server.Git.password={密码}
2 .pom 文件主要内容
- <dependencies>
- <dependency>
- <groupId>org.springframework.cloud</groupId>
- <artifactId>spring-cloud-config-server</artifactId>
- </dependency>
- </dependencies>
3. 启动类
- @SpringBootApplication
- @EnableConfigServer
- public class App
- {
- public static void main( String[] args )
- {
- SpringApplication.run(App.class, args) ;
- }
- }
二. ConfigClient 即配置应用端 , 一般就是具体的要用到全局配置信息的项目
1. Bootstrap.YAML 文件, 由于配置统一放在 Git 服务器上, 所以各个应用就无需使用 application.YAML 或者 application.properties 文件
- spring:
- application:
- name: mockservices
- cloud:
- config:
- uri: http://127.0.0.1:8888
- label: branch1 // 表示具体应用配置仓库中哪个分支
2. 应用配置的代码
- @RunWith(SpringRunner.class)
- @SpringBootTest(classes = MockApp.class)
- public class ConfigTest {
- @Value("${name}")
- private String name ;
- @Test
- public void test() {
- System.out.println(name);
- }
- }
3. pom 文件的必要配置
- <dependencyManagement>
- <dependencies>
- <dependency>
- <groupId>org.springframework.cloud</groupId>
- <artifactId>spring-cloud-dependencies</artifactId>
- <version>${spring-cloud.version}</version>
- <type>pom</type>
- <scope>import</scope>
- </dependency>
- </dependencies>
- </dependencyManagement>
- <dependencies>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-test</artifactId>
- </dependency>
- <dependency>
- <groupId>org.springframework.cloud</groupId>
- <artifactId>spring-cloud-starter-config</artifactId>
- </dependency>
- </dependencies>
来源: http://www.bubuko.com/infodetail-3090882.html