分布式配置中心 SpringCloud Config
Spring Cloud Config 为分布式系统中的为服务提供集中化配置的支持; 分为客户端和服务端,服务端也称为配置中心,是一个独立的微服务应用,用来连接配置仓库并为客户端提供配置信息、加密/解密信息等访问接口;客户端则是为服务架构中的各个微服务应用,它通过配置中心获取仓库中的配置信息。
构建Config Server 配置中心
1、 引入pom
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
2、 在主程序主类中添加@EnableConfigServer 主类
@SpringBootApplication
@EnableConfigServer
@EnableDiscoveryClient
public class ConfigServer01Application {
public static void main(String[] args) {
SpringApplication.run(ConfigServer01Application.class, args);
}
}
3、在yml 配置服务的基本信息以及Git仓库的基本信息
spring:
cloud:
config:
server:
git:
uri: https://gitee.com/pldev/spring-cloud-config
application:
name: config-server01
server:
port: 9090
eureka:
client:
service-url:
defaultZone: http://localhost:8081/eureka/
spring.cloud.config.server.git.uri 配置Git仓库位置
在Git 创建master ,并添加配置文件 pl-dev.yml,
这时我们可以通过 http://192.168.1.112:9090/pl-default.yml,访问配置信息
在请求配置文件时, 会将配置文件拉取到本地, 可以通过basedir 配置
定位服务资源的策略
/{application}/{profile}[/{label}]
/{application}-{profile}.yml
/{label}/{application}-{profile}.yml
/{application}-{profile}.properties
/{label}/{application}-{profile}.properties
application : 应用名称
profile : 环境
label : 仓库的分支
创建config client 客户端
1、 引入pom 配置文件
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-client</artifactId>
</dependency>
2、 配置bootstrap.properties ,这个地方用yml 测试没有成功
spring.application.name=config-client
spring.cloud.config.label=master
spring.cloud.config.profile=dev
spring.cloud.config.discovery.service-id=CONFIG-SERVER01
spring.cloud.config.uri= http://localhost:9090/
server.port=9092
3、 配置远程仓库
eureka:
client:
service-url:
defaultZone: http://localhost:8081/eureka/
instance:
prefer-ip-address: true
SpringCloud Bus
ConfigServier 服务端
1、 引入POM 配置文件
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>
2、 修改application.yml 配置文件
management:
endpoints:
web:
exposure:
include: bus-refresh
security:
enabled: false
rabbitMq 的配置 不使用默认配置可以使用一下配置mq
spring.rabbitmq.host=127.0.0.1
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
ConfigClient 客户端
引用pom
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>
在配置应用的类加入注解@RefreshScope
@RestController
@Configuration
@RefreshScope
public class Demo {
@Value("${test}")
private String name;
@RequestMapping("/show")
public String show(){
return name;
}
}
在ConfigServer 和 ConfigClient 启动后可以通过指令来更新配置文件
curl -X POST http://localhost:9090/bus/refresh
也可以通过WebHooks 更新配置文件