existとの接続をプールする

commons-pool-1.3.jar を使用して、eXistとの接続をプールしてみました。

ExistCollectionFactory.java


import org.apache.commons.pool.BasePoolableObjectFactory;
import org.xmldb.api.DatabaseManager;
import org.xmldb.api.base.Collection;
import org.xmldb.api.base.Database;

public class ExistCollectionFactory extends BasePoolableObjectFactory{

	private static String driver = "org.exist.xmldb.DatabaseImpl";
	private static String url = "xmldb:exist://localhost:8080/exist/xmlrpc/db/";
	private static String user = "admin";
	private static String pass = "";
	
	public static void setProperty(String driver, String url, String user, String pass){
		ExistCollectionFactory.driver = driver;
		ExistCollectionFactory.url = url;
		ExistCollectionFactory.user = user;
		ExistCollectionFactory.pass = pass;
	}
	
    public ExistCollectionFactory(){
    }

    /**
     * @return 生成したオブジェクト。
     */
    public Object makeObject() throws Exception {
    	Collection col = null;
        Class c = Class.forName(driver);
        Database database = (Database) c.newInstance();
        DatabaseManager.registerDatabase(database);
        
        col = DatabaseManager.getCollection(url,user,pass);

        return col;
    }
}

Pooler.java

import org.apache.commons.pool.ObjectPool;
import org.apache.commons.pool.PoolableObjectFactory;
import org.apache.commons.pool.impl.SoftReferenceObjectPool;
import org.xmldb.api.base.Collection;


public class Pooler {
	
	ObjectPool pool = null;
	
	public Pooler(){
	    try {
	        // オブジェクトプールの管理クラスのインスタンスを生成します。
	        PoolableObjectFactory factory = new ExistCollectionFactory();

	        // オブジェクトプールのインスタンスを生成します。
	        pool = new SoftReferenceObjectPool(factory);
	      } catch (Throwable t) {
	        throw new RuntimeException(t);
	      }
	}
	
	public Collection getObject(){
		try {
			return (Collection)pool.borrowObject();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	public void returnObject(Object obj){
		try {
			pool.returnObject(obj);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

使い方

ExistCollectionFactory.setProperty("org.exist.xmldb.DatabaseImpl",
		"xmldb:exist://dugong:8080/exist/xmlrpc/db/test",
		"admin",
		"");
Pooler pooler = new Pooler();

try{
	Collection col = pooler.getObject();
	XMLResource res = (XMLResource)col.getResource("test.xml");
} catch(Exception e){
}

■参考URL
Commonsでオブジェクトプーリングを実現
http://www.atmarkit.co.jp/fjava/rensai2/jakarta05/jakarta05.html




もどる