一:背景
一个项目在多个环境的配置可能不一样,比如数据源,线程池配置等等,那么我们项目代码上不同环境时怎么办,总不能上一个环境改一次代码吧。。。
maven就为我们提供了一个解决方案,profile+filter,什么意思呢,且看下文,O(∩_∩)O哈哈~
二:案例
我在做项目时,要配一个线程池,当然不同环境的线程数和队列数是不一样的,
<bean id="taskExcutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
<property name ="corePoolSize" value = "${threadPool.corePoolSize}" />
<property name ="keepAliveSeconds" value ="${threadPool.keepAliveSeconds}" />
<property name ="maxPoolSize" value ="${threadPool.maxPoolSize}" />
<property name ="queueCapacity" value ="${threadPool.queueCapacity}" />
</bean>
上面的变量部分,不同的环境对应不同的配置文件
1.开发环境---->config-dev.properties
threadPool.corePoolSize = 5
threadPool.keepAliveSeconds = 30000
threadPool.maxPoolSize = 1000
threadPool.queueCapacity = 200
2.测试环境---->config-test.properties
threadPool.corePoolSize = 10
threadPool.keepAliveSeconds = 20000
threadPool.maxPoolSize = 100
threadPool.queueCapacity = 2000
3.生产环境---->config-prod.properties
threadPool.corePoolSize = 3
threadPool.keepAliveSeconds = 3000
threadPool.maxPoolSize = 100
threadPool.queueCapacity = 20
4.最最重要的是pom部分
主要两部分配置,即之前说的profile+filter
<profiles>
<!-- 开发环境 -->
<profile>
<id>dev</id>
<properties>
<env>dev</env>
</properties>
<activation>
<!-- 表示默认用开发环境的配置 -->
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<!-- 测试环境 -->
<profile>
<id>test</id>
<properties>
<env>test</env>
</properties>
</profile>
<!-- 生产环境 -->
<profile>
<id>prod</id>
<properties>
<env>prod</env>
</properties>
</profile>
</profiles>
<!-- 表示src/main/resources/biz这个目录下的文件遇到变量都会用src/main/resources/config/config-${env}.properties里面的内容去替换 -->
<!-- ${env}见最上面的profile配置 -->
<resources>
<resource>
<directory>src/main/resources/biz</directory>
<filtering>true</filtering>
</resource>
</resources>
<filters>
<filter>src/main/resources/config/config-${env}.properties</filter>
</filters>
上面的部分是写在build标签下面的
四:打包
打包命令:mvn package -P${env};${env}就是之前在pom里面配置的env变量,如mvn package -Pprod,打完包后里面的属性配置就可以看到已经被成功的替换成config-prod.properties中的值