减少springboot启动时间
问题背景
项目是基于springboot+mybatis+jooq,依赖的第三方较少,代码也较少,但是每次idea启动时需要100s左右,速度非常慢,每次调试很不方便,所以抽了个时间来做下速度的优化

2.优化思路
先日志级别调为debug级别,分析一下主要的耗时在哪几个地方
发现了几处可能导致启动变慢的地方



通过debug日志我们看到,这三个地方可能潜在耗时的可能,然后逐一定位解决
第一处:
注入dslContext的时候很慢,需要分析为什么很慢

然后通过条件断点,找到耗时的代码块

在进行aop生成代理对象的时候执行时间很长,继续跟踪

扫描DefaultDSLContext类的所有方法,判断是否要对其生成代理,当然最后结果是不需要,但是因为这个类里面有800+的方法,每个都要进行校验,速度很慢,大概需要40s左右,耗费了很长时间,所以在aop中排除掉这个类,使其进行不扫描就解决了这个问题

第二处:

设置了时间后,会有周期任务删除那些空闲时间超过10s的链接,这个时间10s太小,可以设置大点例如100s,修改之后该日志不再出现
第三处:
发现耗时的地方在这里

获取该机器的外网地址,这个操作会很耗时,此处代码会调用多次(6-8次),每次调用都需要耗时6-10s左右,总耗时在40-60s之间,本地调试完全没必要,直接设置成127.0.0.1
百度看了下解决方案

配置本机hostname对应的ip地址,避免代码里面连接网络去获取ip地址,然后去看了下docker镜像是否有这个问题

docker镜像此问题没出现,然后查看下hosts文件

docker镜像/etc/hosts文件会自动写入这个内容,避免了InetAddress.getLocalHost().getHostName()获取耗时的问题,所以docker环境不存在这个问题,这也是为什么docker环境以前启动耗时比本地快的原因(本地启动100s左右,docker环境50s)

优化后本地启动减少到10s左右
