解释如何在 GraalVM 原生镜像中保留 WebSocket 的 CGLIB 代理
解读
国内大厂在 Spring Boot 3.x + GraalVM 云原生落地时,WebSocket 端点(@ServerEndpoint 或 WebSocketHandler)往往依赖 CGLIB 动态代理 实现子类化与依赖注入。GraalVM 的 静态编译 会剔除所有运行时生成的字节码,导致启动报 ClassNotFoundException: xxx$$SpringCGLIB$$FastClass 或 WebSocketContainer Not Available。
面试官真正想考察的是:
- 你是否理解 CGLIB 代理在 WebSocket 生命周期中的触发时机;
- 能否给出 国内可落地的、不破坏原生编译的保留方案,而不是简单回答“加配置”。
知识点
- CGLIB 代理触发点:Spring 为
@ServerEndpoint创建单例 Bean 时,若类含@Autowired等注解且无接口,则默认使用 CGLIB 生成子类;WebSocketHandler同理。 - GraalVM 编译约束:
- 所有运行时生成的类必须在 编译期通过 hint 显式注册;
- CGLIB 的
FastClass、FastMethod需要 反射、资源、序列化 三合一 hint; - native-image 默认关闭 动态代理,需手动开启并指定代理接口列表。
- 国内常用组件差异:
- Spring Boot 3.2+ 已内置
spring-aot插件,可自动生成proxy-config.json、reflect-config.json; - 内嵌 Tomcat/Jetty 在 native 下需额外把
javax.websocket.*的类注册到 resource bundle; - 阿里云函数计算、腾讯云 Serverless 要求最终镜像 < 100 MB,hint 必须 精确到方法级别,不能全量扫描。
- Spring Boot 3.2+ 已内置
答案
步骤一:确认代理范围
在 src/main/resources/META-INF/native-image 下新建 proxy-config.json,只保留 WebSocket 相关的 CGLIB 子类,示例:
[
{
"name": "com.example.ws.ChatEndpoint",
"allDeclaredConstructors": true,
"allDeclaredMethods": true,
"interfaces": ["javax.websocket.Endpoint"]
}
]
步骤二:注册反射条目
同一目录新建 reflect-config.json,把 CGLIB 生成的辅助类 一并声明:
[
{
"name": "com.example.ws.ChatEndpoint$$SpringCGLIB$$0",
"allDeclaredFields": true,
"allDeclaredMethods": true,
"methods": [
{"name": "<init>", "parameterTypes": []}
]
},
{
"name": "org.springframework.web.socket.server.standard.SpringConfigurator",
"methods": [
{"name": "getEndpointInstance", "parameterTypes": ["java.lang.Class"]}
]
}
]
步骤三:在 pom.xml 中开启 agent 收集
<plugin>
<groupId>org.graalvm.buildtools</groupId>
<artifactId>native-maven-plugin</artifactId>
<configuration>
<buildArgs>
<buildArg>--initialize-at-build-time=org.springframework.util.unit.DataSize</buildArg>
<buildArg>--features=org.springframework.aot.nativex.feature.PreComputeFieldFeature</buildArg>
</buildArgs>
</configuration>
</plugin>
运行 mvn -Pnative spring-boot:build-image 前,先以普通 jar 启动一次应用,让 GraalVM agent 自动把缺失的 CGLIB 类 dump 到 target/native-config,再手动合并到上面的 json,避免过度膨胀。
步骤四:验证
使用 native-image-inspector --tool:check 确认 无 Missing class 警告;通过 wrk -d30s -t4 -c200 压测 WebSocket 连接,QPS 下降 < 5 % 即达标。
拓展思考
- JDK 代理替代方案:若 WebSocket 端点实现接口,可强制使用 JDK 动态代理,在
application.properties加spring.aop.proxy-target-class=false,此时只需在proxy-config.json中声明接口数组,镜像体积可再降 8 %。 - 静态编译时代理消除:Spring 6.2 提供
AotProxyUtils.registerStaticProxy,可在编译期直接生成子类字节码,彻底摆脱 CGLIB,国内头部券商已在试点。 - 云厂商限制:华为云 CCE 要求镜像启动时间 < 50 ms,可把
javax.websocket.Session相关类编译到 snapshot 镜像,通过-H:+AllowIncompleteClasspath关闭严格检查,启动时间再缩短 30 %,但需自行承担运行时反射失败风险。