使用spring-loaded開源項目,實現java程序和web應用的熱部署


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的情況下。實現應用的熱部署。




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM