spring-boot
有一個根據JVM
變數-Dspring.profiles.active
來設定執行時的active profile的功能,但是有些時候我們也許會不小心忘記設定這個變數,這樣在生產環境中會帶來一定的困擾,所以我想了一個辦法,來給忘記設定-Dspring.profiles.active
的程式設計師一次“secend chance”。
先來講一下思路:
- step0 約定好profiles的命名,“development”代表開發環境(也可以將預設的profile設為開發環境),“production”代表生產環境
- step1 判斷是否設定了
-Dspring.profiles.active
,如果已經設定,直接跳轉step3
- step2 判斷當前作業系統環境,如果不是Linux環境則認定為開發環境,自動倒數計時啟用開發的profile;如果是Linux環境則認定為生產環境,輸出選擇profile的控制檯資訊,並等待使用者控制檯輸入進行選擇,並依據使用者選擇來啟用profile
- step3
SpringApplication.run()
程式碼如下:
spring-boot配置檔案(使用了預設profile作為開發環境):
spring:
application:
name: comchangyoueurekaserver #注意命名要符合RFC 2396,否則會影響服務發現 詳見https://stackoverflow.com/questions/37062828/spring-cloud-brixton-rc2-eureka-feign-or-rest-template-configuration-not-wor
server:
port: 8001
eureka:
instance:
hostname: localhost
client:
registerWithEureka: false
fetchRegistry: false
serviceUrl:
defaultZone: http://${eureka.instance.hostname}:${server.port}
---
spring:
profiles: production
application:
name: comchangyoueurekaserver
server:
port: 8001
eureka:
instance:
hostname: localhost
client:
registerWithEureka: false
fetchRegistry: false
serviceUrl:
defaultZone: http://${eureka.instance.hostname}:${server.port}
複製程式碼
BootStarter
封裝了step1
-step3
的邏輯:
import org.apache.commons.lang3.StringUtils;
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Pattern;
public class BootStarter {
//用於後續Spring Boot操作的回撥
public interface Callback {
void bootRun();
}
private boolean enableAutomaticallyStart = true;
private int automaticallyStartDelay = 10;
public boolean isEnableAutomaticallyStart() {
return enableAutomaticallyStart;
}
public void setEnableAutomaticallyStart(boolean enableAutomaticallyStart) {
this.enableAutomaticallyStart = enableAutomaticallyStart;
}
public int getAutomaticallyStartDelay() {
return automaticallyStartDelay;
}
public void setAutomaticallyStartDelay(int automaticallyStartDelay) {
this.automaticallyStartDelay = automaticallyStartDelay;
}
public void startup(boolean enableAutomaticallyStart, int automaticallyStartDelay, Callback callback) {
if (StringUtils.isBlank(System.getProperty("spring.profiles.active"))) { //如果沒有通過引數spring.profiles.active設定active profile則讓使用者在控制檯自己選擇
System.out.println("***Please choose active profile:***\n\tp: production\n\td: development");
final boolean[] started = {false};
Timer timer = new Timer();
if (enableAutomaticallyStart && System.getProperty("os.name").lastIndexOf("Linux") == -1) { //如果當前作業系統環境為非Linux環境(一般為開發環境)則automaticallyStartDelay秒後自動設定為開發環境
System.out.printf("\nSystem will automatically select 'd' in %d seconds.\n", automaticallyStartDelay);
final int[] count = {automaticallyStartDelay};
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
if (count[0]-- == 0) {
timer.cancel();
started[0] = true;
System.setProperty("spring.profiles.active", "development");
callback.bootRun();
}
}
}, 0, 1000);
}
Scanner scanner = new Scanner(System.in);
Pattern pattern = Pattern.compile("^p|d$");
//如果是Linux系統(一般為生產環境)則強制等待使用者輸入(一般是忘記設定spring.profiles.active了,這等於給了設定active profile的"second chance")
while (scanner.hasNextLine()) {
if (started[0]) {
break;
}
String line = scanner.nextLine();
if (!pattern.matcher(line).find()) {
System.out.println("INVALID INPUT!");
} else {
timer.cancel();
System.setProperty("spring.profiles.active", line.equals("d") ? "development" : "production");
callback.bootRun();
break;
}
}
} else { //如果已經通過引數spring.profiles.active設定了active profile直接啟動
callback.bootRun();
}
}
public void startup(Callback callback) {
startup(this.enableAutomaticallyStart, this.automaticallyStartDelay, callback);
}
}
複製程式碼
main():
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
import org.springframework.context.ApplicationContext;
@EnableEurekaServer
@SpringBootApplication
public class App {
private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
public static void main(String[] args) {
new BootStarter().startup(() -> {
ApplicationContext applicationContext = SpringApplication.run(App.class, args);
for (String activeProfile : applicationContext.getEnvironment().getActiveProfiles()) {
LOGGER.warn("***Running with profile: {}***", activeProfile);
}
});
}
}
複製程式碼
執行效果(開發環境Mac OS):
擴充套件:
其實在這裡我們還可以發散一下思維,基於spring-boot的應用比起傳統spring應用的一大優勢是自己可以掌控main()
方法,有了這一點,我們是能玩出很多花樣來的,思路不要被侷限在tomcat
時代了。
main法在手,天下我有。
2017-1-22更新:增加了執行緒安全的處理
import org.apache.commons.lang3.StringUtils;
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Pattern;
public class BootStarter {
private volatile boolean started;
//用於後續Spring Boot操作的回撥
public interface Callback {
void bootRun();
}
private boolean enableAutomaticallyStart = true;
private int automaticallyStartDelay = 3;
public boolean isEnableAutomaticallyStart() {
return enableAutomaticallyStart;
}
public void setEnableAutomaticallyStart(boolean enableAutomaticallyStart) {
this.enableAutomaticallyStart = enableAutomaticallyStart;
}
public int getAutomaticallyStartDelay() {
return automaticallyStartDelay;
}
public void setAutomaticallyStartDelay(int automaticallyStartDelay) {
this.automaticallyStartDelay = automaticallyStartDelay;
}
public void startup(boolean enableAutomaticallyStart, int automaticallyStartDelay, Callback callback) {
if (StringUtils.isBlank(System.getProperty("spring.profiles.active"))) { //如果沒有通過引數spring.profiles.active設定active profile則讓使用者在控制檯自己選擇
System.out.println("***Please choose active profile:***\n\tp: production\n\td: development");
Timer timer = new Timer();
if (enableAutomaticallyStart && System.getProperty("os.name").lastIndexOf("Linux") == -1) { //如果當前作業系統環境為非Linux環境(一般為開發環境)則automaticallyStartDelay秒後自動設定為開發環境
System.out.printf("\nSystem will automatically select 'd' in %d seconds.\n", automaticallyStartDelay);
timer.scheduleAtFixedRate(new TimerTask() {
private ThreadLocal<Integer> countDown = ThreadLocal.withInitial(() -> automaticallyStartDelay);
@Override
public void run() {
if (countDown.get() == 0) {
timer.cancel();
started = true;
System.setProperty("spring.profiles.active", "development");
callback.bootRun();
}
countDown.set(countDown.get() - 1);
}
}, 0, 1000);
}
Scanner scanner = new Scanner(System.in);
Pattern pattern = Pattern.compile("^p|d$");
//如果是Linux系統(一般為生產環境)則強制等待使用者輸入(一般是忘記設定spring.profiles.active了,這等於給了設定active profile的"second chance")
while (scanner.hasNextLine()) {
if (started) {
break;
}
String line = scanner.nextLine();
if (!pattern.matcher(line).find()) {
System.out.println("INVALID INPUT!");
} else {
timer.cancel();
System.setProperty("spring.profiles.active", line.equals("d") ? "development" : "production");
callback.bootRun();
break;
}
}
} else { //如果已經通過引數spring.profiles.active設定了active profile直接啟動
callback.bootRun();
}
}
public void startup(Callback callback) {
startup(this.enableAutomaticallyStart, this.automaticallyStartDelay, callback);
}
}
複製程式碼
2017-01-25更新:
補上了 try-with-resource
import org.apache.commons.lang3.StringUtils;
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Pattern;
public class BootStarter {
private volatile boolean started;
//用於後續Spring Boot操作的回撥
public interface Callback {
void bootRun();
}
private boolean enableAutomaticallyStart = true;
private int automaticallyStartDelay = 3;
public boolean isEnableAutomaticallyStart() {
return enableAutomaticallyStart;
}
public void setEnableAutomaticallyStart(boolean enableAutomaticallyStart) {
this.enableAutomaticallyStart = enableAutomaticallyStart;
}
public int getAutomaticallyStartDelay() {
return automaticallyStartDelay;
}
public void setAutomaticallyStartDelay(int automaticallyStartDelay) {
this.automaticallyStartDelay = automaticallyStartDelay;
}
public void startup(boolean enableAutomaticallyStart, int automaticallyStartDelay, Callback callback) {
if (StringUtils.isBlank(System.getProperty("spring.profiles.active"))) { //如果沒有通過引數spring.profiles.active設定active profile則讓使用者在控制檯自己選擇
System.out.println("***Please choose active profile:***\n\tp: production\n\td: development");
Timer timer = new Timer();
if (enableAutomaticallyStart && System.getProperty("os.name").lastIndexOf("Linux") == -1) { //如果當前作業系統環境為非Linux環境(一般為開發環境)則automaticallyStartDelay秒後自動設定為開發環境
System.out.printf("\nSystem will automatically select 'd' in %d seconds.\n", automaticallyStartDelay);
timer.scheduleAtFixedRate(new TimerTask() {
private ThreadLocal<Integer> countDown = ThreadLocal.withInitial(() -> automaticallyStartDelay);
@Override
public void run() {
if (countDown.get() == 0) {
timer.cancel();
started = true;
System.setProperty("spring.profiles.active", "development");
callback.bootRun();
}
countDown.set(countDown.get() - 1);
}
}, 0, 1000);
}
try (Scanner scanner = new Scanner(System.in)) {
Pattern pattern = Pattern.compile("^p|d$");
//如果是Linux系統(一般為生產環境)則強制等待使用者輸入(一般是忘記設定spring.profiles.active了,這等於給了設定active profile的"second chance")
while (scanner.hasNextLine()) {
if (started) {
break;
}
String line = scanner.nextLine();
if (!pattern.matcher(line).find()) {
System.out.println("INVALID INPUT!");
} else {
timer.cancel();
System.setProperty("spring.profiles.active", line.equals("d") ? "development" : "production");
callback.bootRun();
break;
}
}
}
} else { //如果已經通過引數spring.profiles.active設定了active profile直接啟動
callback.bootRun();
}
}
public void startup(Callback callback) {
startup(this.enableAutomaticallyStart, this.automaticallyStartDelay, callback);
}
}
複製程式碼