工作中的各种问题杂记
一、数据库 / MyBatis
1. MyBatis 查询比 DBeaver 慢:分页插件的 count 查询所致
现象:同样的 SQL 通过 DBeaver 等工具执行很快,通过 MyBatis 代码执行却很慢。
原因:MyBatis 中使用了分页插件,实际除了执行目标 SQL,还会执行一条 count 查询记录总条数;这个 count 特别慢,导致整体看起来这个 SQL 特别慢。
排查思路:开启 SQL 日志,分别对比“目标 SQL 耗时”与“count 耗时”确认瓶颈;再针对 count 优化(加索引、改写 SQL 等)。
二、内存泄漏 / OOM 排查
2. 启动 Runner 查大表无分页导致 OOM
现象:应用内存异常升高。
原因:代码中写了一个 Runner,在应用启动后去查一张表,但该表特别大,直接 list 没有分页,导致一直从数据库加载数据到本地内存,引发内存溢出(OOM)。
排查方法:用 jmap 生成 dump 文件,用 Eclipse MAT 打开分析 dump,定位异常原因。
教训:大数据量查询必须分页;启动任务前要评估数据量。
3. Spring Integration 轮询间隔过短导致 OOM
现象:Spring Integration 的轮询间隔设为 0.01s,程序跑一段时间后 OOM。
排查方法:开启 OOM 自动转储 dump,再分析 dump 得出结论。
OOM 自动转储 dump 的启动参数:
nohup /home/jdk/jdk-17.0.2/bin/java -Xmx20480m -Xms5120m \
-XX:+HeapDumpOnOutOfMemoryError \
-XX:HeapDumpPath=/data/test_sca_cloud/collection-runner/dump/ \
-jar ${BASE_PATH}/sca-cloud-collection-runner.jar \
>> ${BASE_PATH}/sca-cloud-collection-runner${formatted_datetime}.log 2>&1 &
⚠️ 参数顺序很关键:
-jar后面必须紧跟 jar 包路径,所有-XX:参数要写在-jar之前。如果写成-jar -XX:+HeapDumpOnOutOfMemoryError ... xxx.jar,JVM 会把-XX:+HeapDumpOnOutOfMemoryError当成 jar 文件名,直接报Unable to access jarfile,程序根本起不来,OOM 自动转储也不会生效。另外
-Xms5120m与-Xmx20480m相差 4 倍,堆会随负载反复扩容收缩,建议把-Xms设得接近-Xmx,减少扩容抖动。
提示:轮询间隔过短会导致任务生产速度远超消费速度,队列积压、内存暴涨,需结合实际处理能力评估间隔。
4. 内存泄漏标准排查流程(jmap / jcmd / MAT)
步骤 1:生成堆转储(dump)
- JDK 8 及以下(
jmap自 JDK 9 起被标记过时,未来可能移除):
jmap -dump:live,format=b,file=heapdump.hprof <pid>
参数说明:
-
-dump:指定生成堆转储; -
live:只转储存活对象,减小文件且更利于分析; -
format=b:使用 HPROF 二进制格式; -
file=heapdump.hprof:输出文件名和路径。 -
JDK 9 及以上推荐
jcmd:
jcmd <pid> GC.heap_dump /data/test_sca_cloud/collection-runner/dump/heapdump.hprof
实践对比:jmap 执行时程序会明显 Stop The World 几秒,jcmd 的停顿则短得多(个人实测)。
注意:
jcmd GC.heap_dump默认同样是“只转储存活对象”,也需要先走到安全点做一次 Full GC,并不是完全没有停顿,只是实测停顿比jmap明显更短。
步骤 2:分析 dump
用 Eclipse MAT 分析 dump 文件,查看哪个类、哪个对象占用大部分内存,再定位到代码。
RES 回落的原因:执行 dump 前 RES(常驻内存)是 14.7G,执行后降到 6.7G。这是因为 -dump:live 会在转储前先做一次 Full GC、只保留存活对象,内存自然回落;jcmd GC.heap_dump 默认行为同理(加 -all 才是连不可达对象一起全量转储、不做 GC)。
次要猜测(未确认,仅备查):直接字节缓冲区
java.nio.ByteBuffer.allocateDirect被清理。代码一直在访问外部网络下载资料,正常来说缓冲区应该会被回收,此条暂无法确认。
5. 扫描程序内存泄漏:Antlr4 包
现象:扫描任务(Python 加密算法扫描场景)运行时发现内存泄漏。
原因:通过 dump 分析定位到 Antlr4 包的问题——使用 Antlr 生成的语法解析器处理多个文件后,PredictionContextCache 中的 HashMap 和 DFA 数组 _decisionToDFA 会不断增长,因为它们在其生成的 Parser 和 Lexer 中是类共享的。
参考:https://www.victorchu.info/posts/fb60a93e/
三、JVM 调优与 GC
6. 查看当前垃圾回收器
jcmd <pid> VM.flags | grep Use
7. 新生代调优
- 应用创建大量短生命周期对象时,较大的新生代可减少 Minor GC 的频率。
- 吞吐量优先 → 新生代调大;响应时间优先 → 新生代调小,使 GC 更快。
经验法则:
- 默认:新生代通常占整个堆的 1/3 ~ 1/2;
- 高吞吐:新生代设为堆的 50% 左右;
- 低延迟:新生代设为 25% ~ 33%。
配置示例(8GB 堆,新生代占 40%):
java -Xms8g -Xmx8g -Xmn3200m -jar your-application.jar
或按老年代 : 新生代 = 2 : 1:
java -Xms8g -Xmx8g -XX:NewRatio=2 -jar your-application.jar
G1 GC 可用 -XX:MaxGCPauseMillis 设置目标最大暂停时间,由 G1 据此自动调整新生代等参数。
调优方法:开启 GC 日志观察后再调整 JVM 参数;可用 GCViewer、VisualVM、GCEasy 分析 GC 日志。
8. GC 日志配置
JDK 8 及以下:
java -Xloggc:/path/to/gc.log \
-XX:+PrintGCDetails \
-XX:+PrintGCDateStamps \
-XX:+PrintTenuringDistribution \
-XX:+PrintHeapAtGC \
-jar your-application.jar
参数说明:
-Xloggc:<file>:GC 日志文件位置;-XX:+PrintGCDetails:输出详细 GC 事件信息;-XX:+PrintGCDateStamps:为每条日志加时间戳;-XX:+PrintTenuringDistribution:显示新生代对象年龄分布;-XX:+PrintHeapAtGC:每次 GC 前后打印堆状态。
JDK 9 及以上(统一使用 -Xlog):
java -Xlog:gc*:file=/path/to/gc.log:time,uptime,pid,tid,level,tags \
-jar your-application.jar
说明:
gc*:记录所有 GC 相关日志;file=...:日志文件路径;time/uptime/pid/tid/level/tags:分别记录事件时间、JVM 启动时长、进程 ID、线程 ID、日志级别、标签(如 [gc]、[heap])。
四、Redis 运维
9. 配置文件位置
/etc/redis/redis.conf
10. Redis 挂掉排查 SOP
现象:周一发现 Redis 服务挂了(以 10.80.0.110 为例)。
排查步骤:
- 查 Redis 自身日志(默认路径
/var/log/redis/),发现大量 "Background saving terminated by signal 9",即 RDB 后台保存被 SIGKILL 强制终止:
1314:M 14 Dec 2024 03:10:14.975 * Background saving terminated with success
1314:M 14 Dec 2024 03:11:15.088 * 10000 changes in 60 seconds. Saving...
1314:M 14 Dec 2024 03:11:17.670 * Background saving started by pid 55961
1314:M 14 Dec 2024 03:11:38.611 # Background saving terminated by signal 9
1314:M 14 Dec 2024 03:11:38.717 * 10000 changes in 60 seconds. Saving...
1314:M 14 Dec 2024 03:11:40.162 * Background saving started by pid 56055
1314:M 14 Dec 2024 03:11:44.540 # Background saving terminated by signal 9
1314:M 14 Dec 2024 03:11:44.641 * 10000 changes in 60 seconds. Saving...
1314:M 14 Dec 2024 03:11:45.883 * Background saving started by pid 56096
1314:M 14 Dec 2024 03:11:50.264 # Background saving terminated by signal 9
1314:M 14 Dec 2024 03:11:50.365 * 10000 changes in 60 seconds. Saving...
1314:M 14 Dec 2024 03:11:51.594 * Background saving started by pid 56122
1314:M 14 Dec 2024 03:11:58.268 # Background saving terminated by signal 9
1314:M 14 Dec 2024 03:11:58.429 * 10000 changes in 60 seconds. Saving...
1314:M 14 Dec 2024 03:12:02.550 * Background saving started by pid 56408
1314:M 14 Dec 2024 03:12:04.300 # Background saving terminated by signal 9
1314:M 14 Dec 2024 03:12:04.402 * 10000 changes in 60 seconds. Saving...
1314:M 14 Dec 2024 03:12:05.608 * Background saving started by pid 56432
1314:M 14 Dec 2024 03:12:09.012 # Background saving terminated by signal 9
1314:M 14 Dec 2024 03:12:10.189 * 10000 changes in 60 seconds. Saving...
1314:M 14 Dec 2024 03:12:11.418 * Background saving started by pid 56451
1314:M 14 Dec 2024 03:12:15.452 # Background saving terminated by signal 9
1314:M 14 Dec 2024 03:12:16.054 * 10000 changes in 60 seconds. Saving...
1314:M 14 Dec 2024 03:12:17.247 * Background saving started by pid 56484
1314:M 14 Dec 2024 03:12:20.334 # Background saving terminated by signal 9
1314:M 14 Dec 2024 03:12:22.039 * 10000 changes in 60 seconds. Saving...
1314:M 14 Dec 2024 03:12:23.315 * Background saving started by pid 56510
1314:M 14 Dec 2024 03:12:28.179 # Background saving terminated by signal 9
1314:M 14 Dec 2024 03:12:28.283 * 10000 changes in 60 seconds. Saving...
1314:M 14 Dec 2024 03:12:29.849 * Background saving started by pid 56528
1314:M 14 Dec 2024 03:12:33.726 # Background saving terminated by signal 9
1314:M 14 Dec 2024 03:12:34.028 * 10000 changes in 60 seconds. Saving...
1314:M 14 Dec 2024 03:12:35.353 * Background saving started by pid 56552
- 查 systemd 日志:
journalctl -u redis.service
典型输出:
12月 24 16:48:25 sca-test systemd[1]: redis.service: main process exited, code=killed, status=9/KILL
12月 24 16:48:25 sca-test systemd[1]: Unit redis.service entered failed state.
12月 24 16:48:25 sca-test systemd[1]: redis.service failed.
status=9/KILL 说明是被外部 kill 信号强杀。
- 查系统日志确认是否 OOM Killer 所为:
cat /var/log/messages | grep redis-server
典型输出:
Dec 24 16:48:18 sca-test kernel: [91678] 997 91678 13843305 11023178 26748 0 0 redis-server
Dec 24 16:48:18 sca-test kernel: [50455] 997 50455 13843405 11025648 26741 0 0 redis-server
Dec 24 16:48:18 sca-test kernel: Out of memory: Kill process 50455 (redis-server) score 335 or sacrifice child
Dec 24 16:48:18 sca-test kernel: Killed process 50455 (redis-server), UID 997, total-vm:55373620kB, anon-rss:44102592kB, file-rss:0kB, shmem-rss:0kB
Dec 24 16:48:18 sca-test kernel: [91678] 997 91678 13843305 11023178 26748 0 0 redis-server
Dec 24 16:48:18 sca-test kernel: Out of memory: Kill process 91678 (redis-server) score 335 or sacrifice child
Dec 24 16:48:18 sca-test kernel: Killed process 91678 (redis-server), UID 997, total-vm:55373220kB, anon-rss:44092712kB, file-rss:0kB, shmem-rss:0kB
结论:Redis 因系统内存不足触发 OOM Killer 被强杀(SIGKILL 不给进程清理资源或执行退出逻辑的机会,通常来自人工 kill 或 OOM Killer)。从内核日志看 anon-rss 已达 44GB、score 335 被选中,属于典型的整机内存耗尽。
为什么会 OOM(推断):日志中 Saving... 与 signal 9 高频交替出现,指向 RDB 后台保存。Redis 执行 BGSAVE 会 fork 出子进程,copy-on-write 期间父进程的写入会触发页复制,内存占用接近翻倍;如果实例本身已接近机器内存上限,fork 叠加 CoW 就会把整机内存打满,从而被 OOM Killer 挑中。
后续:检查代码是否存在内存泄漏(写爆 Redis 的源头)。
11. Redis 重启超时:RDB 过大
现象:Redis 因 OOM 挂掉后重启一直失败:
Job for redis.service failed because a timeout was exceeded. See "systemctl status redis.service" and "journalctl -xe" for details.
原因:Redis 本身数据有 62G,RDB 数据量过大,启动时加载 RDB 耗时超过 systemd 默认超时时间。
解决:修改 /usr/lib/systemd/system/redis.service,加大启动超时:
[Service]
TimeoutStartSec=600
再次重启 OK。
备选:
TimeoutStartSec=0表示完全不限制启动时间,适合 RDB 特别大、加载时间不可预估的场景;缺点是 Redis 真的启动失败时 systemd 不会报错,只能靠日志判断。补充:修改 unit 文件后需先执行
systemctl daemon-reload再重启,配置才会生效。
五、Spring Cloud / Nacos
12. Nacos 推送后应用刷新报错:jar 包被替换
现象:使用 Nacos 修改配置后,程序无法正确收到推送,报错:
2024-12-24T11:00:42.417+08:00 INFO 14816 --- [ternal.notifier] c.a.nacos.client.config.impl.CacheData : [fixed-test-10.80.0.110_8848] [notify-context] dataId=sca-cloud-collection-runner, group=DEFAULT_GROUP, md5=31543b0a7e0575521d01df87cd21f227
2024-12-24T11:00:42.419+08:00 ERROR 14816 --- [ternal.notifier] c.a.nacos.client.config.impl.CacheData : [fixed-test-10.80.0.110_8848] [notify-error] dataId=sca-cloud-collection-runner, group=DEFAULT_GROUP, md5=31543b0a7e0575521d01df87cd21f227, listener=com.alibaba.cloud.nacos.refresh.NacosContextRefresher$1@5bec096d
java.lang.IllegalArgumentException: Unable to load factories from location [META-INF/spring.factories]
at org.springframework.core.io.support.SpringFactoriesLoader.loadFactoriesResource(SpringFactoriesLoader.java:353) ~[spring-core-6.0.13.jar!/:6.0.13]
at org.springframework.core.io.support.SpringFactoriesLoader.lambda$forResourceLocation$2(SpringFactoriesLoader.java:333) ~[spring-core-6.0.13.jar!/:6.0.13]
at java.base/java.util.concurrent.ConcurrentMap.computeIfAbsent(ConcurrentMap.java:330) ~[na:na]
at org.springframework.core.io.support.SpringFactoriesLoader.forResourceLocation(SpringFactoriesLoader.java:332) ~[spring-core-6.0.13.jar!/:6.0.13]
at org.springframework.core.io.support.SpringFactoriesLoader.forDefaultResourceLocation(SpringFactoriesLoader.java:299) ~[spring-core-6.0.13.jar!/:6.0.13]
at org.springframework.boot.SpringApplication.getSpringFactoriesInstances(SpringApplication.java:467) ~[spring-boot-3.1.5.jar!/:3.1.5]
at org.springframework.boot.SpringApplication.getSpringFactoriesInstances(SpringApplication.java:463) ~[spring-boot-3.1.5.jar!/:3.1.5]
at org.springframework.boot.SpringApplication.<init>(SpringApplication.java:275) ~[spring-boot-3.1.5.jar!/:3.1.5]
at org.springframework.boot.builder.SpringApplicationBuilder.createSpringApplication(SpringApplicationBuilder.java:115) ~[spring-boot-3.1.5.jar!/:3.1.5]
at org.springframework.boot.builder.SpringApplicationBuilder.<init>(SpringApplicationBuilder.java:102) ~[spring-boot-3.1.5.jar!/:3.1.5]
at org.springframework.boot.builder.SpringApplicationBuilder.<init>(SpringApplicationBuilder.java:98) ~[spring-boot-3.1.5.jar!/:3.1.5]
at org.springframework.cloud.context.refresh.LegacyContextRefresher.addConfigFilesToEnvironment(LegacyContextRefresher.java:72) ~[spring-cloud-context-4.0.4.jar!/:4.0.4]
at org.springframework.cloud.context.refresh.LegacyContextRefresher.updateEnvironment(LegacyContextRefresher.java:56) ~[spring-cloud-context-4.0.4.jar!/:4.0.4]
at org.springframework.cloud.context.refresh.ContextRefresher.refreshEnvironment(ContextRefresher.java:101) ~[spring-cloud-context-4.0.4.jar!/:4.0.4]
at org.springframework.cloud.context.refresh.ContextRefresher.refresh(ContextRefresher.java:94) ~[spring-cloud-context-4.0.4.jar!/:4.0.4]
at org.springframework.cloud.endpoint.event.RefreshEventListener.handle(RefreshEventListener.java:72) ~[spring-cloud-context-4.0.4.jar!/:4.0.4]
at org.springframework.cloud.endpoint.event.RefreshEventListener.onApplicationEvent(RefreshEventListener.java:61) ~[spring-cloud-context-4.0.4.jar!/:4.0.4]
at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:174) ~[spring-context-6.0.13.jar!/:6.0.13]
at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:167) ~[spring-context-6.0.13.jar!/:6.0.13]
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:145) ~[spring-context-6.0.13.jar!/:6.0.13]
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:445) ~[spring-context-6.0.13.jar!/:6.0.13]
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:378) ~[spring-context-6.0.13.jar!/:6.0.13]
at com.alibaba.cloud.nacos.refresh.NacosContextRefresher$1.innerReceive(NacosContextRefresher.java:118) ~[spring-cloud-starter-alibaba-nacos-config-2022.0.0.0.jar!/:2022.0.0.0]
at com.alibaba.nacos.api.config.listener.AbstractSharedListener.receiveConfigInfo(AbstractSharedListener.java:40) ~[nacos-client-2.2.1.jar!/:na]
at com.alibaba.nacos.client.config.impl.CacheData.lambda$safeNotifyListener$1(CacheData.java:334) ~[nacos-client-2.2.1.jar!/:na]
at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:539) ~[na:na]
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) ~[na:na]
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1136) ~[na:na]
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635) ~[na:na]
at java.base/java.lang.Thread.run(Thread.java:833) ~[na:na]
Caused by: java.util.zip.ZipException: invalid block type
at java.base/java.util.zip.InflaterInputStream.read(InflaterInputStream.java:164) ~[na:na]
at org.springframework.boot.loader.jar.ZipInflaterInputStream.read(ZipInflaterInputStream.java:52) ~[sca-cloud-collection-runner.jar:1.0-SNAPSHOT]
at java.base/java.io.FilterInputStream.read(FilterInputStream.java:106) ~[na:na]
at java.base/java.util.Properties$LineReader.readLine(Properties.java:503) ~[na:na]
at java.base/java.util.Properties.load0(Properties.java:419) ~[na:na]
at java.base/java.util.Properties.load(Properties.java:408) ~[na:na]
at org.springframework.core.io.support.PropertiesLoaderUtils.fillProperties(PropertiesLoaderUtils.java:140) ~[spring-core-6.0.13.jar!/:6.0.13]
at org.springframework.core.io.support.PropertiesLoaderUtils.loadProperties(PropertiesLoaderUtils.java:123) ~[spring-core-6.0.13.jar!/:6.0.13]
at org.springframework.core.io.support.SpringFactoriesLoader.loadFactoriesResource(SpringFactoriesLoader.java:342) ~[spring-core-6.0.13.jar!/:6.0.13]
关键点:SpringFactoriesLoader 读取 jar 内 META-INF/spring.factories 时抛 ZipException: invalid block type,即解压读取 jar 失败。
涉及版本(便于复现):spring-boot 3.1.5、spring-context / spring-core 6.0.13、spring-cloud-context 4.0.4、spring-cloud-starter-alibaba-nacos-config 2022.0.0.0、nacos-client 2.2.1。
原因:在推送配置之前,把新打包的 jar 上传到了服务器、替换了原 jar 包,导致运行中的程序再读取 jar 内文件时出错。
教训:运行中程序的 jar 不能被替换;流程应为先修改配置,再上传 jar 包(或先停服务再替换)。
六、线程池
13. 自定义线程池拒绝策略
实现 RejectedExecutionHandler 接口即可,方法里能拿到任务和线程池,可自由定义处理逻辑(记录日志、重试、降级等):
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
// 自定义处理逻辑
}
14. 线程池命名,便于排查
public static ExecutorService indexExecutor = new ThreadPoolExecutor(
10, 20,
60L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>(1000),
new ThreadFactoryBuilder().setNameFormat("index-query-pool-%d").build(),
new ThreadPoolExecutor.AbortPolicy());
注:
ThreadFactoryBuilder来自 Guava;keepAliveTime的单位是毫秒,这里60L只有 60ms,如果本意是 60 秒应改为TimeUnit.SECONDS。
七、序列化
15. Serializable 要实现到父类上
场景:做源码下载时发现。
如果使用 Serializable 实现序列化,只让子类实现该接口,父类中的字段不会被序列化。应让父类实现 Serializable 接口(或改用 JSON 等其他序列化方案)。
八、开发工具与 Git
16. IDEA 无法识别 Maven 项目
现象:重新从仓库 clone 代码后,IDEA 打开无法自动识别为 Maven 项目,IDEA 中完全没有 Maven 相关操作。
原因:源码里有 .idea 文件夹,包含别人的配置,导致异常。
解决:删除 .idea 文件夹,重新用 IDEA 打开生成自己的配置即可。
17. Git 合并冲突无法解决时取消合并
git merge --abort
九、Linux 常用命令
18. 查看 Java 进程打开的网络连接
lsof -i -n | grep <pid> # 查看该进程的网络连接
lsof -i -n | grep <pid> | grep <IP> | wc -l # 统计该进程到某 IP 的连接数
(原例:pid 80215、IP 151.101.108.223)
19. 查看容器资源与 CPU 信息
docker stats | grep runner # 查看容器资源使用情况
lscpu # 查看 CPU 信息、核数
评论