一、契子
很早以前就開始構(gòu)思可動態(tài)部署的Web應(yīng)用,模塊化應(yīng)用無疑是一種趨勢,Portal應(yīng)用可謂是一個小革新,它的功能引起了很多人的注意,OSGi 無疑會為這帶來本質(zhì)上的升級。二、目標(biāo)
這篇blog中的例子從JPetStoreOsgi衍生,通過擴(kuò)展(修改)Spring mvc中的某些對象,實現(xiàn)模塊的動態(tài)部署,當(dāng)然,這只是很簡單的案例,不過足以達(dá)到我的預(yù)期目標(biāo):有2個非常簡單的模塊module1和module2,它們都有自己的Spring mvc配置文件,可以在運(yùn)行時簡單的通過OSGi控制臺,安裝它們,并完成它們各自的功能。
三、準(zhǔn)備工作
[點(diǎn)擊這里下載 DynamicModule 工程包]
由于整個Workspace太大,所以僅僅只是把更新的5個Bundle的Project上傳了,先 下載JPetStoreOsgi ,然后將所有關(guān)于JPetStore的Project刪除,導(dǎo)入這5個Project
四、Spring MVC
目前還沒有用于OSGi環(huán)境的MVC框架,所以選用Spring MVC做為演示框架
org.phrancol.osgi.demo.mvc.springmvc 是整個應(yīng)用的MVC Bundle,以下簡稱 MVCBundle
- org.phrancol.osgi.demo.mvc.springmvc.core.HandlerRegister
public interface HandlerRegister {
/**
* 當(dāng)bundle的ApplicationContext生成后,獲取HandlerMapping,并注冊
* @param context Spring為Bundle生成的ApplicationContext
* @param bundle
*/
public void registerHandler(ApplicationContext context, Bundle bundle);
/**
* 當(dāng)Bundle被停止或是卸載的時候,注銷這個bundle的HandlerMapping
* 當(dāng)然這個功能沒有實現(xiàn)(它可以實現(xiàn)),因為他不屬于演示范圍
* @param bundle
*/
public void unRegisterHandler(Bundle bundle);
}
- 擴(kuò)展DispatcherServlet - org.phrancol.osgi.demo.mvc.springmvc.core.OsgiDispatcherServlet
同時,它還充當(dāng)一個HandlerMapping注冊管理器的角色,通過一個BundleHandlerMappingManager來管理bundle的HandlerMapping,包括動態(tài)添加/刪除等,它會重寫DispatcherServlet 的getHandler方法,從BundleHandlerMappingManager獲取Handler.....這里的代碼比較簡單,一看就能明白。BundleHandlerMappingManager只是一個Map的簡單操作,代碼省略
public class OsgiDispatcherServlet extends DispatcherServlet implements
HandlerRegister {
private static final Log log = LogFactory
.getLog(OsgiDispatcherServlet.class);
/* HandlerMapping管理對象 */
private BundleHandlerMappingManager bundleHandlerMappingManager;
private BundleContext bundleContext;
public OsgiDispatcherServlet(BundleContext bundleContext) {
this.bundleContext = bundleContext;
this.bundleHandlerMappingManager = new BundleHandlerMappingManager();
}
protected WebApplicationContext createWebApplicationContext(
WebApplicationContext parent) throws BeansException {
ClassLoader contextClassLoader = Thread.currentThread()
.getContextClassLoader();
try {
ClassLoader cl = BundleDelegatingClassLoader
.createBundleClassLoaderFor(bundleContext.getBundle(),
getClass().getClassLoader());
Thread.currentThread().setContextClassLoader(cl);
LocalBundleContext.setContext(bundleContext);
ConfigurableWebApplicationContext wac = new OSGiXmlWebApplicationContext(
bundleContext);
wac.setParent(parent);
wac.setServletContext(getServletContext());
wac.setServletConfig(getServletConfig());
wac.setNamespace(getNamespace());
if (getContextConfigLocation() != null) {
wac
.setConfigLocations(StringUtils
.tokenizeToStringArray(
getContextConfigLocation(),
ConfigurableWebApplicationContext.CONFIG_LOCATION_DELIMITERS));
}
wac.addApplicationListener(this);
wac.refresh();
return wac;
} finally {
Thread.currentThread().setContextClassLoader(contextClassLoader);
}
}
/**
* 重寫這個方法是很有必要的
*/
protected HandlerExecutionChain getHandler(HttpServletRequest request,
boolean cache) throws Exception {
HandlerExecutionChain handler = (HandlerExecutionChain) request
.getAttribute(HANDLER_EXECUTION_CHAIN_ATTRIBUTE);
if (handler != null) {
if (!cache) {
request.removeAttribute(HANDLER_EXECUTION_CHAIN_ATTRIBUTE);
}
return handler;
}
for (Iterator _it = this.bundleHandlerMappingManager
.getBundlesHandlerMapping().values().iterator(); _it.hasNext();) {
List _handlerMappings = (List) _it.next();
for (Iterator it = _handlerMappings.iterator(); it.hasNext();) {
HandlerMapping hm = (HandlerMapping) it.next();
if (logger.isDebugEnabled()) {
logger.debug("Testing handler map [" + hm
+ "] in OsgiDispatcherServlet with name '"
+ getServletName() + "'");
}
handler = hm.getHandler(request);
if (handler != null) {
if (cache) {
request.setAttribute(HANDLER_EXECUTION_CHAIN_ATTRIBUTE,
handler);
}
return handler;
}
}
}
return null;
}
/**
* 這個功能實現(xiàn)起來有點(diǎn)牽強(qiáng),但是以演示為主,一笑而過
*/
protected View resolveViewName(String viewName, Map model, Locale locale,
HttpServletRequest request) throws Exception {
long bundleId = this.bundleHandlerMappingManager.getBundleId(request);
Bundle bundle = this.bundleContext.getBundle(bundleId);
ViewResolver viewResolver = new OsgiInternalResourceViewResolver(
bundle, getWebApplicationContext(), viewName);
View view = viewResolver.resolveViewName(viewName, locale);
return view;
}
public void registerHandler(ApplicationContext context, Bundle bundle) {
Map matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(
context, HandlerMapping.class, true, false);
if (!matchingBeans.isEmpty()) {
List _list = new ArrayList(matchingBeans.values());
String bundleId = new Long(bundle.getBundleId()).toString();
this.bundleHandlerMappingManager.registerHandlerMapping(bundleId,
_list);
}
}
public void unRegisterHandler(Bundle bundle){
String bundleId = new Long(bundle.getBundleId()).toString();
this.bundleHandlerMappingManager.unRegisterHandlerMapping(bundleId);
}
}
- 擴(kuò)展InternalResourceViewResolver - org.phrancol.osgi.demo.mvc.springmvc.core.OsgiInternalResourceViewResolver
為了方便,這部份的代碼寫得有些不地道(演示為主~),重寫getPrefix()方法,主要是為了獲取jsp文件
public class OsgiInternalResourceViewResolver extends
InternalResourceViewResolver {
private static final Log log = LogFactory.getLog(OsgiInternalResourceViewResolver.class);
private static final String PREFIX = "/web/jsp/spring/";
private static final String SUFFIX = ".jsp";
private String viewName;
private Bundle bundle;
public OsgiInternalResourceViewResolver(Bundle bundle, ApplicationContext applicationContext , String viewName){
this.bundle = bundle;
setPrefix(PREFIX);
setSuffix(SUFFIX);
setViewClass(new JstlView().getClass());
setApplicationContext(applicationContext);
this.bundle = bundle;
this.viewName = viewName;
}
protected String getPrefix() {
String _prefix= "/"+bundle.getSymbolicName()+PREFIX;
return _prefix;
}
}
- MVCBundle需要設(shè)置一個Activator,用于將OsgiDispatcherServlet注冊為OSGi Service
public void start(BundleContext bundleContext) throws Exception {
DispatcherServlet ds = new OsgiDispatcherServlet(bundleContext);
bundleContext.registerService(DispatcherServlet.class.getName(), ds,
null);
}
- MVCBundle中的SpringmvcHttpServiceRegister還是需要的,它需要生成一個所謂的容器Context
public class SpringmvcHttpServiceRegister implements HttpServiceRegister {
public void serviceRegister(BundleContext context,
ApplicationContext bundleApplicationContext) {
try {
ServiceReference sr = context.getServiceReference(HttpService.class
.getName());
HttpService httpService = (HttpService) context.getService(sr);
HttpContext defaultContext = httpService.createDefaultHttpContext();
Dictionary<String, String> initparams = new Hashtable<String, String>();
initparams.put("load-on-startup", "1");
/**/
ContextLoaderServlet contextloaderListener = new BundleContextLoaderServlet(
context, bundleApplicationContext);
httpService.registerServlet("/initContext", contextloaderListener,
initparams, defaultContext);
/**/
DispatcherServlet dispatcherServlet = (DispatcherServlet) context
.getService(context
.getServiceReference(DispatcherServlet.class
.getName()));
/* 這里給了 DispatcherServlet 一個空的配置文件,可以節(jié)省好多代碼*/
dispatcherServlet
.setContextConfigLocation("META-INF/dispatcher/DynamicModule-servlet.xml");
initparams = new Hashtable<String, String>();
initparams.put("servlet-name", "DynamicModule");
initparams.put("load-on-startup", "2");
httpService.registerServlet("/*.do", dispatcherServlet, initparams,
defaultContext);
} catch (Exception e) {
e.printStackTrace(System.out);
}
}
}
通過以上工作,Spring MVC就被簡單的改造完了......當(dāng)然他僅僅只是能實現(xiàn)我所要演示的功能
五、模塊
新建一個模塊bundle - org.phrancol.osgi.demo.mvc.springmvc.module2 ,Bundle-SymbolicName設(shè)置為module2
先看看它的bean配置




















也使用了一個SpringmvcHttpServiceRegister,它就是用來注冊這個bundle 中的jsp和資源的

































來看看org.phrancol.osgi.demo.mvc.springmvc.module2.TheSecondModuleController ,只有很簡單的一個輸出













目錄結(jié)構(gòu)也有一點(diǎn)變化 /module1/web/jsp/spring/ *.jsp
模塊1和模塊2是一樣的
六、運(yùn)行
將模塊二導(dǎo)出為bundle jar包,放到C盤根目錄下,啟動這個應(yīng)用(當(dāng)然不要啟動modure2),在瀏覽器看看module1的運(yùn)行情況
現(xiàn)在安裝一下module2
試著訪問一下module2
404,正常,啟動一下這個bundle再看看
顯示出來了,現(xiàn)在可以動態(tài)的操作這2個模塊了......
七、擴(kuò)展
通過這個演示,可以領(lǐng)略到OSGi帶給我們的一小部分功能,做一些擴(kuò)展看看
1. 當(dāng)然是各種框架的支持。
2. 強(qiáng)大的bundle資源庫
3. 絕對動態(tài)的部署框架,可以通過UI界面來操作。
4. 可以從URL來安裝bundle, install http://www.domain.com/sampleBundle.jar ,如果是這樣的,服務(wù)網(wǎng)關(guān)就能體現(xiàn)出來了,你提供一個服務(wù)框架,別人可以通過你的框架運(yùn)行自己的服務(wù)。
5. 個人猜測,它將取代Portal的運(yùn)行模式
6. ..........
八、結(jié)束語
OSGi在Web應(yīng)用中還有很長的路要走,它到底會發(fā)展成什么樣子,就目前的功能還真不好推測。
現(xiàn)在不管是MVC還是持久層都還沒有框架對OSGi的支持,我個人準(zhǔn)備用業(yè)余時間研究一下這方面,順便也可以練練手,希望傳說中的強(qiáng)人能開發(fā)這樣的框架并不吝開源~
九、相關(guān)資源
就我目前能找到的一些資源,列出如下:Struts2有一個OSGi的插件,但是我看了看,并不能達(dá)到預(yù)期效果,不過可以看一看
http://cwiki.apache.org/S2PLUGINS/osgi-plugin.html
在持久層方面,db4o似乎有這個打算,不做評論
http://www.db4o.com/osgi/
另外它的合作伙伴prosyst已經(jīng)開發(fā)出了一個基于Equinox的OSGi Server,還有個專業(yè)版,好像要收費(fèi),所以也就沒下載,不知道是個什么樣子。
http://www.prosyst.com/