JDK1.5之后提供了java.lang.instrument.Instrumentation,即java agent机制可以实现类的redefinition和retransform。
redefinition相应Instrumentation.redefineClasses()可以实现类的热替换。但遗憾的是功能非常有限。
The redefinition may change method bodies, the constant pool and attributes.
The redefinition must not add, remove or rename fields or methods, change the
signatures of methods, or change inheritance. These restrictions maybe be
lifted in future versions.
近期遇到一个开源项目spring-loaded,看了下官方的介绍文档:发现它功能比JDK自带的强大多了。
Spring Loaded is a JVM agent for reloading class file changes whilst a JVM is running.
It transforms classes at loadtime to make them amenable to later reloading.
Unlike 'hot code replace' which only allows simple changes once a JVM is running
(e.g. changes to method bodies), Spring Loaded allows you to
add/modify/delete methods/fields/constructors.
The annotations on types/methods/fields/constructors
can also be modified and it is possible to add/remove/change values in enum types.
经过自己的尝试,发现使用spring-loaded项目。确实能够实现java应用的热部署。以下介绍下怎样将spring-loaded引入到项目中。
我们能够执行以下的这段代码,然后改动A.say()方法,看看在不重新启动JVM的情况下,能否够动态改变。
package test;
import demo.A;
public class TestPreMain
{
// -javaagent:springloaded-1.2.0.RELEASE.jar -noverify
public static void main(String[] args) throws Exception
{
A a = new A();
while (true)
{
a.say();
Thread.sleep(3000);
}
}
}
为了使用spring-loaded实现热部署。我们仅仅须要在启动JVM的时候。添加例如以下的启动參数就可以
-javaagent:springloaded-1.2.0.RELEASE.jar -noverify
假设是通过eclipse启动,那么能够在run confiuration中进行设置
接下来我们看下怎样在tomcat中使用spring-loaded实现war包的热部署。将下载的springloaded-1.2.0.RELEASE.jar放到%TOMCAT_HOME%/bin/文件夹下,然后改动该文件夹下的catalina.bat
set JAVA_OPTS=-javaagent:springloaded-1.2.0.RELEASE.jar -noverify
这样就完毕了spring-loaded的安装,可以检測tomcat下部署的webapp,在不重新启动tomcat的情况下。实现应用的热部署。