spring-cloud-config-server
1.概述
Spring Cloud Config Server为分布式系统中的外部化配置提供服务器端和客户端支持。可以集中管理所有环境中应用程序的外部属性,服务器的存储默认使用 git。
2.远程仓库结构如下
3.搭建服务项目
(1)引入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
(2)编写连接远程仓库的配置文件application.properties
server.port=9090
#服务的名称
spring.application.name=config-single-server
#git地址
spring.cloud.config.server.git.uri=https://codeup.aliyun.com/62d7ab97487c500c27f23a97/project-config-center.git
#用户名
spring.cloud.config.server.git.username=aliyun8321553713_z1FYL
#密码
spring.cloud.config.server.git.password=XXX12345
#分支
spring.cloud.config.server.git.default-label=master
#git仓库里面的路径
spring.cloud.config.server.git.search-paths=config
(3)启动类上加上@EnableConfigServer表示这是一个注册中心
package com.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.config.server.EnableConfigServer;
@SpringBootApplication
@EnableConfigServer
public class SpringCloudConfigServerApp {
public static void main(String[] args) {
SpringApplication.run(SpringCloudConfigServerApp.class, args);
}
}
4.搭建客户端项目
(1)引入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>
(2)先写application.properties这个配置文件主要作用就是写配置文件的名字和程序运行的端口
server.port=8202
spring.application.name=beimao
再写bootstrap.properties配置文件,这个配置文件的作用是在程序启动之前,获取到信息
#这个配置文件的作用是在程序启动之前,获取到信息
# 分支
spring.cloud.config.label=master
# cloud server 地址
spring.cloud.config.uri=http://localhost:9090/
#要请求那个名称的远程文件,多个用逗号分隔. 和下面profile连接就会访问application-dev.properties
spring.cloud.config.name=beimao
# profile
spring.cloud.config.profile=test
(3)编写一个测试类,证明可以获取远程配置文件的内容
package com.example.controlller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@Value("${user}")
private String girl;
@GetMapping("/test")
public String test(){
return this.girl;
}
}