boot spring 一直转 启动_java小工具-使用springboot-starter启动检查配置是否满足要求...

随着项目迭代,新组件加入使配置和环境切分复杂,开发人员启动项目耗时久。为此开发小工具,封装成Spring Boot starter,启动时检查配置和环境,检测项包括环境变量、Java运行变量、指定位置文件和host等,并以Apollo检测为例编写检查代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

9d51fc7c6a7633b169a7337f7f0139a9.png

项目背景

随着项目不断的迭代,不断的有新的组件加入进来,比如现在项目中就集成了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'}

项目结构如下图所示

6da9ddb0a66937ef6f20227a76a9a18b.png

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"); }}

运行效果如下:

ef8babb4f0f77f856bc29dd68fd64e8e.png

这样我们就做到了在项目一启动的时候就运行检测代码的效果

编写检查代码

如上所述有环境变量,文件等简单的校验,本文以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 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值