Skip to main content

profile 多环境切换

介绍

无需修改代码实现(开发、测试、部署)配置间的切换。

概念介绍

profile 支持概要文件的概念,它允许您在不同的环境中轻松地组织配置(由概要文件定义)。 看看下面的配置,来自我们的一个真实项目。

resources
└── conf
├── common
│ ├── db.props
│ └── other.props
├── local
│ └── db.props
└── production
├── db.props
└── other.props

假设在 local 服务器上,你用 JVM 选项 -Diohao.profile=local 启动应用程序,将按照以下顺序加载配置

  1. 读取 /resources/conf/common 目录下的所有 .props 文件
  2. 读取 /resources/conf/local 目录下所有的 .props 文件

这样,使用 local 配置文件中定义的配置项来覆盖公共配置文件中定义的相同配置项,未被覆盖的公共项仍然有效。

如何安装

由于 profile 是单独的、按需选择的功能模块,使用时需要在 pom.xml 中引入

see https://central.sonatype.com/artifact/com.iohao.game/light-profile

pom.xml
<dependency>
<groupId>com.iohao.game</groupId>
<artifactId>light-profile</artifactId>
<version>${ioGame.version}</version>
</dependency>

Example

如果你的应用不是 spring 项目,可以通过下面的方式来选择启动配置环境 profile。

  • code 5,加载环境配置。
  • code 8 ~ 10,调用配置文件中的配置。
public class ProfileManagerTest {
@Test
public void profile() {
String profileConfigName = "local";
ProfileManager.loadMainProfile(profileConfigName);

Profile profile = ProfileManager.profile();
String jdbcDriver = profile.get("jdbcDriver");
boolean devMode = profile.getBool("devMode");
int maxVip = profile.getInt("maxVip");

log.info("{} {} {}", jdbcDriver, devMode, maxVip);
}
}

Spring Example

假设你的项目部署到了你的 local 服务器,你可以使用 JVM 参数 --iohao.profile=local 来启动应用。

java -jar yourApp.jar --iohao.profile=local
@Override
public void setEnvironment(Environment env) {
String profileConfigName = env.getProperty("iohao.profile");
ProfileManager.loadMainProfile(profileConfigName);
}