SpringCloud中配置管理中心
前言
配置管理中心可以为所有微服务提供一个统一的配置管理服务, 微服务可以使用本地工程的配置, 也可以使用配置管理中心的配置, 当这两个方面具有相同的配置项时, 系统默认优先使用配置管理中心所提供的配置
对于分布式应用来说, 可能有多个环境, 每个环境或许都是一套配置, 那么这时候管理起来相对来说就非常不便, 我们使用配置管理中心就能够使我们的分布式应用减轻配置冗余, 提高我们的开发效率
创建仓库
我们需要在Github/Gitee上创建一个专门用来存放我们配置文件的仓库,在这里我选择的是国内的Gitee仓库,创建仓库,然后存放我们编写的配置文件YML/Properties
创建配置管理中心
我们在我们的父工程下创建一个子模块 base-config
, 然后我们需要在 POM.XML
文件中引入如下依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
我们在启动类上面添加注解@EnableConfigServer
来声明这是一个配置中心服务
之后我们进行配置
在项目中的application.yml中
server:
port: 8888
spring:
application:
name: base-config-server
cloud:
config:
server:
git:
uri: https://gitee.com/Seale6/SpringConfigTest
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
启动后我们通过浏览器访问地址:http://localhost:8888/application-test.yml
或者http://localhost:8888/application/test
然后会出现以下数据
{
"name":"application",
"profiles":[
"test"
],
"label":null,
"version":"072ec6002ac19b42ef2fd349327047a211d6107a",
"state":null,
"propertySources":[
{
"name":"https://gitee.com/Seale6/SpringConfigTest/application-test.yml",
"source":{
"server.port":8888
}
}
]
}
可以看到其中propertySources.source以下的字段就是我们的配置信息,当然我们可以直接通过http://localhost:8888/application-test.yml访问,那么它会直接读取我们的配置文件
server:
port: 8888
如此配置中心服务也就搭建成功了
配置中心可以访问的的映射规则如下
/{application}/{profile}[/{label}]
/{application}-{profile}.yml
/{label}/{application}-{profile}.yml
/{application}-{profile}.properties
/{label}/{application}-{profile}.properties
创建测试客户端
注意客户端需要添加以下依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
如果成功启动则可忽略!
在启动类中修改代码
@SpringBootApplication
@EnableEurekaClient
@RestController
public class ConfigClientApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigClientApplication.class, args);
}
@Value("${test}")
String test ;
@RequestMapping("/test")
public String test(){
return test;
}
}
我们新建以一个bootstrap.xml
配置文件
spring:
cloud:
config:
name: application
profile: test
uri: http://localhost:8888
application:
name: config-client
解释一下,我们通过配置,设置了config的文件名字前缀为application
,后缀也就是-
后面一块为test
,而在仓库中存放的文件是application-test.yml
,那么我们就能够成功访问并取回test的值
仓库中的配置文件是这样的
server:
port: 8889
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
spring:
application:
name: config-client
test: 123
那么我们访问客户端http://localhost:8889/test
那么则会返回123
如此我们便成功使用了配置中心了,当然这个只是初级阶段!
One comment
非技术的路过。