此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 Spring Framework 6.2.6! |
JVM AOT 缓存
预先缓存是 Java 24 中通过 JEP 483 引入的一项 JVM 功能,有助于减少启动时间和内存 Java 应用程序的占用空间。AOT 缓存是类数据共享 (CDS) 的自然演变。 Spring Framework 同时支持 CDS 和 AOT 缓存,建议您使用 以后,如果在您使用的 JVM 版本 (Java 24+) 中可用。
要使用此功能,应为 应用。可以在部署的实例上创建此缓存,也可以在 例如,在打包应用程序时执行训练运行,这要归功于钩子点 由 Spring Framework 提供,以简化此类用例。缓存可用后,用户 应该通过 JVM 标志选择使用它。
如果您使用的是 Spring Boot,强烈建议利用其可执行 JAR 解包支持,该支持旨在满足 AOT 缓存和 CDS 的类加载要求。 |
创建缓存
通常可以在应用程序退出时创建 AOT 缓存。Spring 框架
提供一种作模式,在该模式下,进程可以在ApplicationContext
已刷新。在此模式下,所有非惰性初始化的单例
已实例化,并且InitializingBean#afterPropertiesSet
回调
调用;但生命周期尚未启动,并且ContextRefreshedEvent
还没有
已发布。
要在训练运行期间创建缓存,可以指定-Dspring.context.exit=onRefresh
JVM 标志启动,然后在 Spring 应用程序执行ApplicationContext
已刷新:
-
AOT cache
-
CDS
# Both commands need to be run with the same classpath
java -XX:AOTMode=record -XX:AOTConfiguration=app.aotconf -Dspring.context.exit=onRefresh ...
java -XX:AOTMode=create -XX:AOTConfiguration=app.aotconf -XX:AOTCache=app.aot ...
# To create a CDS archive, your JDK/JRE must have a base image
java -XX:ArchiveClassesAtExit=app.jsa -Dspring.context.exit=onRefresh ...
使用缓存
创建缓存文件后,您可以使用它来更快地启动应用程序:
-
AOT cache
-
CDS
# With the same classpath (or a superset) tan the training run
java -XX:AOTCache=app.aot ...
# With the same classpath (or a superset) tan the training run
java -XX:SharedArchiveFile=app.jsa ...
注意日志和启动时间,检查 AOT 缓存是否使用成功。
要了解缓存的有效性,您可以通过添加
一个额外的属性:-Xlog:class+load:file=aot-cache.log
.这将创建一个aot-cache.log
跟
每次尝试加载类及其源。从缓存加载的类应具有
“共享对象文件”源,如以下示例所示:
[0.151s][info][class,load] org.springframework.core.env.EnvironmentCapable source: shared objects file
[0.151s][info][class,load] org.springframework.beans.factory.BeanFactory source: shared objects file
[0.151s][info][class,load] org.springframework.beans.factory.ListableBeanFactory source: shared objects file
[0.151s][info][class,load] org.springframework.beans.factory.HierarchicalBeanFactory source: shared objects file
[0.151s][info][class,load] org.springframework.context.MessageSource source: shared objects file
如果无法启用 AOT 缓存,或者您有大量未加载的类 缓存,请确保在创建和使用缓存时满足以下条件:
-
必须使用相同的 JVM。
-
类路径必须指定为 JAR 或 JAR 列表,并避免使用目录和通配符。
*
-
必须保留 JAR 的时间戳。
-
使用缓存时,Classpath 必须与用于创建它的 Classpath 相同,顺序相同。 可以在末尾指定其他 JAR 或目录(但不会缓存)。