运行环境

1
2
3
<java.version>1.8</java.version>
<spring-boot.version>2.3.7.RELEASE</spring-boot.version>
<spring-cloud.version>Hoxton.SR9</spring-cloud.version>

常用 API

查看配置

1
2
const url = `{{ip}}:{{port}}/{{applitionName}}-{{env}}.yml`;
# 如 http://localhost:10001/client-dev.yml

image.png
image.png

本地模式

1
2
3
4
5
6
7
8
9
10
spring:
application:
name: config-server
profiles:
active: native # 本地配置的固定启动环境
cloud:
config:
server:
native:
search-locations: file:///本机地址,支持 classpath

环境异常

当没有指定 spring.profiles.active=native 时,以读取 Git 仓库为配置,出现以下异常:

1
2
3
4
5
6
7
8
9
10
11
***************************
APPLICATION FAILED TO START
***************************

Description:

Invalid config server configuration.

Action:

If you are using the git profile, you need to set a Git URI in your configuration. If you are using a native profile and have spring.cloud.config.server.bootstrap=true, you need to use a composite configuration.

注意:谨防在全局配置了环境变量,由于在系统环境变量中设置了公司常用的环境名,导致配置文件中的激活项被覆盖,而一直无法启动。
image.png

Git 模式

1
2
3
4
5
6
spring:
cloud:
config:
server:
git:
uri: file:///本机地址

本地仓库

支持设置 uri 为本地路径,但需要该仓库存在,并且访问的配置(如:client-dev.yml)已被 git 托管。

远程仓库

1
2
3
4
5
6
7
8
spring:
cloud:
config:
server:
git:
uri: 仓库地址
username: 用户名
password: 密码

加密密码

由于在项目中使用明文配置密码,不太合适,较好的方式使用对其进行加密。

1
2
3
4
5
6
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<!-- 版本号,以 maven 仓库中的配适为准 -->
<version>3.0.4</version>
</dependency>
1
2
3
jasypt:
encryptor:
password: 加密密码

使用方式:

1
2
3
4
5
6
7
8
9
10
11
@Test
void encrypt() {
Assertions.assertDoesNotThrow(() -> {
final String encrypt = stringEncryptor.encrypt("123456");
System.out.println(encrypt);
Assertions.assertEquals(
"123456",
stringEncryptor.decrypt(encrypt)
);
});
}

在程序中打印出加密后的字符串,并在配置文件中使用 ENC() 包裹,标识其为一串加密字符。

1
2
3
### 仅展示密码部分
git:
password: ENC(加密字符)

安全认证

到目前为止,配置中心的所有 api 都是可随意访问的,若需要对公网暴露,则需要添加登录鉴权更安全些。
添加 security 依赖,并简单配置:

1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
1
2
3
4
5
spring:
security:
user:
name: config-server
password: password123

注册中心

1
2
3
4
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
1
2
3
4
eureka:
client:
service-url:
defaultZone: http://ip:port/eureka/

并在启动类上添加 @EnableEurekaClient 注解。

评论