【线上问题】GC时长过长
大黄 Lv4

背景

机器背景:POD内存小,仅1G
业务背景:服务商三方应用,企业微信拉取消息,涉及到对消息key的解密。解密操作代码书写不当,导致大量对象被创建,过早进入老年代,触发FullGC停机

排查思路

问题感知

GC过长系统告警

image.png

Grafana监控显示服务停机

image.png
image.png
image.png

排查流程

查看监控,发现是GC导致

导出堆文件,对堆文件进行分析

image.png
image.png
image.png
由图中可以看出,公私钥加解密实体被过多创建

回顾代码

原来的代码中,每次解密都回去创建一个BouncyCastleProvider对象。
每一条企微消息,都会调用decrypt方法。当消息拉取量过大时,就会导致BouncyCastleProvider对象被过多的创建

1
2
3
4
5
6
7
8
9
10
11
public static String decrypt(String encryptedData, PrivateKey privateKey) throws Exception {
// 初始化RSA解密器
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", new BouncyCastleProvider());
cipher.init(Cipher.DECRYPT_MODE, privateKey);

byte[] encryptedSecretKeyBytes = Base64.getDecoder().decode(encryptedData);
// 解密密文
byte[] decryptedData = cipher.doFinal(encryptedSecretKeyBytes);
// 将解密后的数据转换成字符串进行处理
return new String(decryptedData, StandardCharsets.UTF_8);
}

解决方案

对Cipher增加LRU本地缓存

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
private static Cache<String, Cipher> CACHE = CacheBuilder.newBuilder()
.maximumSize(20)
.expireAfterWrite(10, TimeUnit.MINUTES)
.build();

private static Cipher getCache(String key) {
return CACHE.getIfPresent(key);
}

private static void putCache(String key, Cipher cipher) {
CACHE.put(key, cipher);
}

public static String decryptWithCache(String encryptedData, PrivateKey privateKey, String cacheKey) throws Exception {
Cipher cache = getCache(cacheKey);
if (cache == null) {
// 初始化RSA解密器
cache = Cipher.getInstance("RSA/ECB/PKCS1Padding", new BouncyCastleProvider());
cache.init(Cipher.DECRYPT_MODE, privateKey);
putCache(cacheKey, cache);
}
byte[] encryptedSecretKeyBytes = Base64.getDecoder().decode(encryptedData);
// 解密密文
byte[] decryptedData = cache.doFinal(encryptedSecretKeyBytes);
// 将解密后的数据转换成字符串进行处理
return new String(decryptedData, StandardCharsets.UTF_8);
}

对POD内存调整

增加POD整体内存,扩大年轻代

原配置

1
-Xms1g -Xmx1g -XX:MetaspaceSize=256m -XX:MaxMetaspaceSize=256m -Xmn384m -XX:MaxDirectMemorySize=256m

新配置

1
-Xms2g -Xmx2g -XX:MetaspaceSize=512m -XX:MaxMetaspaceSize=521m -Xmn768m
  • Post title:【线上问题】GC时长过长
  • Post author:大黄
  • Create time:2024-07-13 16:26:51
  • Post link:https://huangbangjing.cn/2024/07/13/【线上问题】GC时长过长/
  • Copyright Notice:All articles in this blog are licensed under BY-NC-SA unless stating additionally.