springboot项目开发、测试、生产环境配置分离,实现配置环境快速切换
概述
由于项目需要本地开发,以及测试服务器进行部署测试,最后进行生产环境的部署。因此需要快速实现项目配置文件的切换,因此进行项目配置分离,按照需要部署的环境,进行项目配置切换。
创建开发、测试、生产环境yml配置文件
1、创建配置文件统一按照 application-开头,开发环境以dev结尾,测试环境以test结尾,生产环境以prod结尾。因此创建三个配置文件名称分别为 application-dev.yml,application-test.yml,application-prod.yml
2、配置环境加载切换入口文件application.yml
springboot项目默认加载application.yml文件为配置文件,因此在application.yml中进行配置文件参数的切换配置
##本地开发环境 dev 线上测试环境 test 线上生产环境 prod
spring:
profiles:
active: dev
3、配置本地开发参数
spring:
datasource:
url: ###
username: ###
password: ###
driver-class-name: com.mysql.cj.jdbc.Driver
application:
name: customer
redis:
host: 127.0.0.1
port: 6380
mybatis-plus:
mapper-locations: classpath:/mapper/*/*.xml
type-aliases-package: com.firstdream.customer.*.entity
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
server:
port: 8083
servlet:
context-path: /customer
# 微服务部分:
eureka:
#eueka 主机名
instance:
prefer-ip-address: true
instance-id: ${spring.application.name}:${spring.application.instance_id:${server.port}}
appname: customer
client:
#提供者和消费者的注册地址
serviceUrl:
defaultZone: http://root:booszy@localhost:8761/eureka
feign:
hystrix:
enabled: true
ribbon:
ReadTimeout: 30000
ConnectTimeout: 15000
hystrix:
command:
default:
execution:
isolation:
strategy: SEMAPHORE
thread:
timeoutInMilliseconds: 10000
socketIo:
win: 192.168.166.107
linxu: 0.0.0.0
port: 9090
maxFramePayloadLength: 1048576
maxHttpContentLength: 1048576
allowCustomRequests: true
upgradeTimeout: 10000
pingTimeout: 180000
pingInterval: 25000
这里仅以dev配置文件为例,进行记录,测试配置文件,以及生产配置文件按照实际项目配置参数进行创建。
4、动态获取不同配置文件中socketIo配置参数
由于项目启动时要根据加载的不同环境的配置文件加载不同的socketIo配置参数,因此需要在项目启动时动态获取到加载的配置文件名称,因此需要在NettySocketConfig 文件中动态获取加载的配置文件名称
public static String ymlType;
@Value("${spring.profiles.active}")
public void setYmlType(String ymlType) {
NettySocketConfig.ymlType = ymlType;
}
由于@Value 不能注解静态属性因此定义一个set方法,进行文件名动态获取。注:配置文件需要配置@Configuration 注解
这样就动态获取到了加载的配置文件名称。