
项目背景
随着项目不断的迭代,不断的有新的组件加入进来,比如现在项目中就集成了cat,apollo,prometheus,docker,k8s等等 , 随之而来的有一大堆host要配置,如redis , mysql , zookeeper等等. 还要切分环境,如DEV, UAT, PROD等等, 开发人员拉到代码的时候,往往还要弄个大半天才能投入开发,因此写了这个小工具,可以在启动时检查一些配置,环境之类的,并提供修复建议
检查配置
主要有以下几个检测项:
1. 环境变量的检查
2. java运行变量的检查
3. 指定位置文件的检查
4. host检查
运行启动
要想一启动程序就运行,我们自然而然就想到了springboot 的 starter 项目,对,我们把这个也封装成一个starter, 这样一启动springboot应用,就可以检查各种条件了.
制作starter
引入依赖:
dependencies {implementation platform('org.springframework.boot:spring-boot-dependencies:2.1.6.RELEASE')compile group: 'org.springframework.boot', name: 'spring-boot-autoconfigure'}
项目结构如下图所示

spring.factories:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.platform.tools.starter.spring.boot.ToolAutoConfigurationorg.springframework.context.ApplicationContextInitializer=com.platform.tools.starter.spring.boot.ToolApplicationContextInitializer
ToolAutoConfiguration.java
@Configurationpublic class ToolAutoConfiguration {}
ToolApplicationContextInitializer.java
public class ToolApplicationContextInitializer implements ApplicationContextInitializer { @Override public void initialize(ConfigurableApplicationContext applicationContext) { System.out.println("write check code here"); }}
运行效果如下:

这样我们就做到了在项目一启动的时候就运行检测代码的效果
编写检查代码
如上所述有环境变量,文件等简单的校验,本文以apollo的检测为例写几个典型的获取配置的代码,下面的代码中包含判断文件是否存在,判断环境变量,判断系统变量
public class InitCheck { /** 操作系统类别: 1是win, 2是其他 */ private Integer osType; /** 环境变量的map */ private Map envMap = System.getenv(); public InitCheck() { //获取操作系统类型 String osName = System.getProperty("os.name"); this.osType = osName.contains("windows")?1:2; } /** * 对外提供的调用方法,在 new 完InitCheck之后,就调用这个方法 * * @return */ public boolean checkAll(){ return checkApollo(); } /** * 检查apollo的配置是否正确 * @return */ private boolean checkApollo(){ //apollo主要是检查ENV有没有设置,而且只检查环境变量和文件 String env = envMap.get("ENV"); boolean envFlag = env != null && !env.isEmpty(); String filePath = osType==1?"C:/opt/settings/server.properties":"/opt/settings/server.properties"; boolean fileFlag = Files.exists(Paths.get(filePath)); boolean result = envFlag || fileFlag; if(!result){ System.out.printf("请正确配置apollo , 设置环境变量 ENV=dev 或者在文件 %s 中写入 ENV=dev