一.简介
SpringCloudConfig是微服务的配置中心,使用git/svn 作为版本管理工具管理配置文件,这样所有的微服务都通过SpringCloudConfig微服务动态获取配置信息。
SpringCloudConfig 微服务注册到Eureka中,而后所有微服务都从SpringCloudConfig微服务中获取配置。
二.Config Server服务端
1.新建一个git仓库并把service-user模块配置信息application.yml提交到服务器 service-user/service-user-prod.yml
server:
port: 8020
spring:
application:
name: service-user #定义微服务名称
eureka:
client:
service-url:
defaultZone: http://admin:admin@localhost:8010/eureka
2.新建config-server配置服务端,引入依赖配置
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
</dependencies>
3.Config Server application.yml配置信息
server:
port: 8060
spring:
application:
name: config-server
cloud:
config:
server:
git:
clone-on-start: true
uri: https://gitee.com/vincent-java-test/spring-cloud-config.git
username: xxx
password: xxx
#配置搜索路径
search-paths:
- service-user
4.编写启动类
package com.vincent.config;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.config.server.EnableConfigServer;
@SpringBootApplication
@EnableConfigServer
public class ConfigServerApp {
public static void main(String[] args) {
SpringApplication.run(ConfigServerApp.class,args);
}
}
通过以下形式访问git中的配置文件:{label}/{application}-{profile}.yml
http://localhost:8060/master/service-user-prod.yml
三.配置信息加密/解密
配置服务增加bootstrap.yaml配置文件配置密钥:
encrypt:
key: ciphertext
访问配置服务 http://localhost:8150/encrypt 即可得到加密密文(原配置服务应用没有了,使用另一个配置服务作为示例说明):
访问配置服务(原配置服务应用没有了,使用另一个配置服务作为示例说明) http://localhost:8150/decrypt
微服务从配置中心获取配置时密文的解密是由配置中心解密
四.从config-server获取配置信息
1.service-user模块引入配置依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
2.service-user模块新建bootstrap.yml 文件
spring:
cloud:
config:
name: service-user
label: master
profile: prod
uri: http://localhost:8060/
application.yml 属于用户级资源配置,bootstrap.yml属于系统级资源配置,其优先级更高。
3.启动service-user模块,并访问 http://localhost:8020/user/9
五.配置刷新
使用配置服务的系统增加actuator依赖并暴露refresh端点
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
1.修改git中存储的配置信息
2.访问服务接口:/actuator/refresh 则会重新获取配置并刷新相关配置
刷新配置后会重新创建被注解@RefreshScope修饰的Bean对象
六.SpringCloudConfig高可用
如果Config Server服务出现问题则所有微服务都将瘫痪,Config Server高可用机制可以避免单主机缺陷。
1.把config-server 注册到Eureka注册中心
2.修改service-user模块bootstrap.yml
spring:
cloud:
config:
name: service-user
label: master
profile: prod
discovery:
enabled: true
service-id: config-server
eureka:
client:
service-url:
defaultZone: http://admin:admin@localhost:8010/eureka
3.访问:http://localhost:8020/user/9