开发过程中,经常出现的环境必定会有以下几个:开发环境、测试环境、预发布环境(可能会有,可能没有)、正式环境;由于这些环境的存在,我们就不得不去维护这一系列环境的配置(如数据库连接、商户资料等等)及版本,那么要如何去管理这些配置呢?
下载地址
server:
port: 8080 #设置项目的端口
spring:
profiles:
active: local #设置项目运行的环境
conf: 本地
conf: 测试
conf: 正式
@RestController
public class ConfController {
@Value("${conf}")
public String conf;
@GetMapping("conf")
public String getConf() {
return conf;
}
}
#java -jar jar文件地址 --spring.profiles.active=环境别名
java -jar target/myconfig.jar --spring.profiles.active=pro
这样同一个版本包即可实现各个环境的切换
业务开发过程中,除了项目的一些基础配置之外,不可避免的会存在一些自定义的业务流程配置;同样也就不可避免的会存在不同环境下的配置文件,以下即演示自定义配置文件的动态切换;
busi:
key: va-all
busi:
key1: va1-local
key2: va2-local
key3:
keyc1: vac1-local
key4:
okey1: ova1-local
okey2: ova2-local
key5: 9,10
busi:
key1: va1-dev
key2: va2-dev
key3:
keyc1: vac1-dev
key4:
okey1: ova1-dev
okey2: ova2-dev
key5: 6,7,8
busi:
key1: va1-pro
key2: va2-pro
key3:
keyc1: vac1-pro
key4:
okey1: ova1-pro
okey2: ova2-pro
key5: 1,2,3,4,5
public class YamlPropertyLoaderFactory extends DefaultPropertySourceFactory {
@Override
public PropertySource> createPropertySource(String name, EncodedResource resource) throws IOException {
if (resource == null) {
return super.createPropertySource(name, resource);
}
return new YamlPropertySourceLoader().load(resource.getResource().getFilename(), resource.getResource()).get(0);
}
}
添加业务配置对象
@Data
@Component
//当前要注入的所有属性的前缀
@ConfigurationProperties(prefix = "busi")
//指定要扫描的文件路径,${spring.profiles.active}用于指定当前运行环境的配置文件
//YamlPropertyLoaderFactory yaml文件加载工厂,默认是使用的propertes加载工厂,如果配置文件后缀是propertes,那么就不用配置factory属性
@PropertySource(value = {"classpath:myconfig/yml-config.yml","classpath:myconfig/yml-config-${spring.profiles.active}.yml"}, encoding = "UTF-8", factory = YamlPropertyLoaderFactory.class)
public class BusiConfig {
private String key;
private String key1;
private String key2;
//以map的形式接受多个子属性
private Map key3;
//以对象接口多个子属性
private OtherConfig key4;
//以列表的形式
private List key5;
}
OtherConfig 对象
@Data
public class OtherConfig {
private String okey1;
private String okey2;
}
@RestController
public class BusiController {
@Autowired
BusiConfig busiConfig;
@GetMapping("busiconf")
public BusiConfig busiConfig(){
return busiConfig;
}
}
既然是使用的同一个包在运行时通过环境变量进行切换,那么如果使用docker的方式运行的时候,要如何配置来实现一个镜像在运行时进行环境切换呢?
FROM hub.c.163.com/library/java:8-alpine
#指明该镜像的作者
MAINTAINER lupf XXX
#添加文件
ADD target/*.jar myconfig.jar
#改镜像监听的端口
EXPOSE 8080
#指定镜像可以像一个可执行文件一样执行
ENTRYPOINT ["java","-jar","-Duser.timezone=GMT 8","/myconfig.jar"]
//构建一个镜像名为: myconfig 版本为:1.0.0的镜像
docker build -t myconfig:1.0.0 .
#docker run -p 端口映射 --name=容器别名 镜像名:版本 --spring.profiles.active=运行环境
docker run -p 8080:8080 --name=myconfig myconfig:1.0.0 --spring.profiles.active=dev
运行容器时通过指定(spring.profiles.active)进行运行时环境切换
到此! 运行时配置文件自动切换即可完成!