分佈式配置中心 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 更新配置文件