实现最简单的配置中心
先在 github 或gitee中建立配置文件
创建配置中心服务端
1、新建 Spring Boot 项目,引入 config-server 和 starter-web
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- spring cloud config 服务端包 -->
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-config-server -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
<version>2.2.5.RELEASE</version>
</dependency>
2、配置 config 相关的配置项
server:
port: 3366
spring:
application:
name: config-single-server # 应用名称
cloud:
config:
server:
git:
uri: https://gitee.com/gitzhoukun/springcloud-config.git #配置文件所在仓库
username: 账号
password: 密码
default-label: master #配置文件分支
search-paths: springcloudstudy/config #配置文件所在根目录
3、在 Application 启动类上增加相关注解 @EnableConfigServer
@SpringBootApplication
@EnableConfigServer
public class configServer {
public static void main(String[] args) {
SpringApplication.run(configServer.class,args);
}
}
启动测试
Spring Cloud Config 有它的一套访问规则,我们通过这套规则在浏览器上直接访问就以。
/{application}/{profile}[/{label}]
/{application}-{profile}.yml
/{label}/{application}-{profile}.yml
/{application}-{profile}.properties
/{label}/{application}-{profile}.properties
http://localhost:3301/text/dev/master
http://localhost:3301/text/prod
http://localhost:3301/text.yml
http://localhost:3301/text.yml
http://localhost:3301/master/text.yml
创建配置中心客户端,使用配置
pom
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- spring cloud config 客户端包 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
<version>2.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
yml
spring:
cloud:
config:
name: text # 应用名称,需要对应git中配置文件名称的前半部分
profile: dev # 开发环境,需要对应git中配置文件名称的后半部分
label: master # 分支名称
uri: http://localhost:3366 # config-server的请求地址
@RestController
public class testcontroller {
@Value("${spring.application.name}")
String applicationName;
@Value("${server.port}")
String serverpost;
@Value("${spring.profiles}")
String profilesprod;
@GetMapping("/config")
public String getConfig(){
return applicationName+","+serverpost+","+profilesprod;
}
}
测试
可以看出访问的是3367端口,但是application.yml里面配置的800端口,可以得出结论
bootstrap权限比application大