演示从配置中心获取配置
·启动config-client服务;
· 访问http://localhost:9001/configInfo,可以获取到dev分支下dev环境的配置;
config info for dev(dev)
获取子目录下的配置
我们不仅可以把每个项目的配置放在不同的Git仓库存储,也可以在一个Git仓库中存储多个项目的配置,此时就会用到在子目录中搜索配置信息的配置。
首先我们需要在config-server中添加相关配置,用于搜索子目录中的配置,这里我们用到了application占位符,表示对于不同的应用,我们从对应应用名称的子目录中搜索配置,比如config子目录中的配置对应config应用。
访问http://localhost:9001/configInfo进行测试,可以发现获取的是config子目录下的配置信息。
config info for config dir dev(dev)
刷新配置
当Git仓库中的配置信息更改后,我们可以通过SpringBoot Actuator的refresh端点来刷新客户端配置信息,以下更改都需要在config-client中进行。
·在pom.xml中添加Actuator的依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
· 在bootstrap.yml中开启refresh端点:
· 在ConfigClientController类添加@RefreshScope注解用于刷新配置:
/**
* Created by macro on 2019/9/11.
*/
@RestController
@RefreshScope
public class ConfigClientController {
@Value("${config.info}")
private String configInfo;
@GetMapping("/configInfo")
public String getConfigInfo() {
return configInfo;
}
}
· 重新启动config-client后,调用refresh端点进行配置刷新:
访问http://localhost:9001/configInfo进行测试,可以发现配置信息已经刷新。
update config info for config dir dev(dev)
配置中心添加安全认证
我们可以通过整合SpringSecurity来为配置中心添加安全认证。
创建config-security-server模块
· 在pom.xml中添加相关依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
· 在application.yml中进行配置:
server:
port: 8905
spring:
application:
name: config-security-server
cloud:
config:
server:
git:
uri: https://gitee.com/macrozheng/springcloud-config.git
username: macro
password: 123456
clone-on-start: true #开启启动时直接从git获取配置
security: #配置用户名和密码
user:
name: macro
password: 123456
启动config-security-server服务。
修改config-client的配置
添加bootstrap-security.yml配置文件,主要是配置了配置中心的用户名和密码:
server:
port: 9002
spring:
application:
name: config-client
cloud:
config:
profile: dev #启用配置后缀名称
label: dev #分支名称
uri: http://localhost:8905 #配置中心地址
name: config #配置文件名称
username: macro
password: 123456
使用bootstrap-security.yml启动config-client服务;
访问http://localhost:9002/configInfo进行测试,发现可以获取到配置信息。
config info for dev(dev)
config-sever集群搭建
在微服务架构中,所有服务都从配置中心获取配置,配置中心一旦宕机,会发生很严重的问题,下面我们搭建一个双节点的配置中心集群来解决该问题。
启动两个config-server分别运行在8902和8903端口上;
添加config-client的配置文件bootstrap-cluster.yml,主要是添加了从注册中心获取配置中心地址的配置并去除了配置中心uri的配置:
spring:
cloud:
config:
profile: dev #启用环境名称
label: dev #分支名称
name: config #配置文件名称
discovery:
enabled: true
service-id: config-server
eureka:
client:
service-url:
defaultZone: http://localhost:8001/eureka/
以bootstrap-cluster.yml启动config-client服务,注册中心显示信息如下:
访问http://localhost:9003/configInfo,发现config-client可以获取到配置信息。
config info for config dir dev(dev)
使用到的模块
springcloud-learning
├── eureka-server -- eureka注册中心
├── config-server -- 配置中心服务
├── config-security-server -- 带安全认证的配置中心服务
└── config-client -- 获取配置的客户端服务
本文内容不用于商业目的,如涉及知识产权问题,请权利人联系51Testing小编(021-64471599-8017),我们将立即处理