概述
在项目部署时,相关的生产环境和测试环境是分开的,但是代码是同一套;
所以一般会有多套变量;
项目中默认变量(一般是测试环境)
线上变量(线上数据较敏感,一般也不会放在代码中)
UAT变量
当前常用的springcloud
中,一般会把nacos
配置放在pom.xml
中,利用maven-compiler-plugin
插件,在maven
编译时替换变量,达到切换nacos
环境的作用,其余的db配置
等都在对应环境的nacos配置
中.
线上的配置一般会放在代码中,我是通过启动时注入的方式,命令行具有最高优先级,可以覆盖所有配置文件中的设置。
参数优先级总结
- 命令行参数:具有最高优先级
- 环境变量:次之
- 配置文件(如
application.yml
):较低优先级 - 默认值:最低优先级
maven编译时替换变量
<dependencies><!-- 使bootstrap.yml配置文件可识别 --><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-bootstrap</artifactId></dependency>
</dependencies><profiles><profile><id>dev</id><properties><!-- 环境标识,需要与配置文件的名称相对应 --><profiles.active>dev</profiles.active><nacos.username>xxx</nacos.username><nacos.password>xxx</nacos.password><nacos.address>xxx.xxx.xxx.xxx:8848</nacos.address><nacos.namespace>xxx-xxx-xxx-xxx-xxx</nacos.namespace><sentinel.dashboard.address>xxx.xxx.xxx.xxx:8858</sentinel.dashboard.address></properties><activation><!-- 默认环境 --><activeByDefault>true</activeByDefault></activation></profile><profile><id>pro</id><properties><profiles.active>pro</profiles.active></properties></profile>
</profiles><build><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>3.10.1</version><configuration><source>${java.version}</source><target>${java.version}</target><encoding>UTF-8</encoding></configuration></plugin></plugins><resources><resource><directory>src/main/resources</directory><!-- 关闭过滤 --><filtering>false</filtering></resource><resource><directory>src/main/resources</directory><!-- 引入所有 匹配文件进行过滤 --><includes><include>bootstrap*</include></includes><!-- 启用过滤 即该资源中的变量将会被过滤器中的值替换 --><filtering>true</filtering></resource></resources>
</build>
maven
编译时替换的变量在bootstrap.yml
中的使用;在maven编译时会替换掉变量中的参数,通过切换生效的profile
标签来达到切换环境的目的
# Spring
spring: profiles:# 环境配置active: @profiles.active@cloud:nacos:discovery:# 服务注册地址server-addr: ${nacos.address}namespace: ${nacos.namespace}group: xxxusername: ${nacos.username}password: ${nacos.password}
JVM 参数、应用程序参数、命令行参数
在java -jar
启动时可以注入参数
# JVM参数
JAVA_OPTS="-Xms8192m -Xmx8192m -XX:MetaspaceSize=256m -XX:MaxMetaspaceSize=256m -XX:+UseConcMarkSweepGC"
# 应用程序参数
PARAMS="--workerId=2 --datacenterId=2"# PARAMS提前定义好的若干应用程序参数,会传递给main方法;springboot做了封装可以注入相应的属性
java -jar $JAVA_OPTS xxx-xxx.jar $PARAMS
后面的PARAMS
参数主要依赖于org.springframework.boot.SpringApplication#run(java.lang.Class<?>, java.lang.String...)
进行变量注入;并且$PARAMS
注入的值可以覆盖yml
中的值
package com.example;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class MyApplication {public static void main(String[] args) {//这里的args就是注入的PARAMS变量SpringApplication.run(MyApplication.class, args);}
}