spring - 创建一个JAXB Unmarshaller池

标签 spring jaxb pool unmarshalling

我一直在寻找一种方法来改善处理大量文件的JAXB解码性能,并发现以下建议:

“如果您真的很在意性能,和/或您的应用程序将要读取很多小文档,那么创建Unmarshaller可能是一项相对昂贵的操作。在这种情况下,请考虑合并Unmarshaller对象”

在网上搜索以查找此示例,但未返回任何内容,因此,我认为使用Spring 3.0和Apache Commons Pool将我的实现放在这里可能会很有趣。
UnmarshallerFactory.java

import java.util.HashMap;
import java.util.Map;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import org.apache.commons.pool.KeyedPoolableObjectFactory;
import org.springframework.stereotype.Component;

/**
 * Pool of JAXB Unmarshallers.
 * 
 */
@Component
public class UnmarshallerFactory implements KeyedPoolableObjectFactory {
    // Map of JAXB Contexts
    @SuppressWarnings("rawtypes")
    private final static Map<Object, JAXBContext> JAXB_CONTEXT_MAP = new HashMap<Object, JAXBContext>();

    @Override
    public void activateObject(final Object arg0, final Object arg1) throws Exception {
    }

    @Override
    public void passivateObject(final Object arg0, final Object arg1) throws Exception {
    }

    @Override
    public final void destroyObject(final Object key, final Object object) throws Exception {
    }

    /**
     * Create a new instance of Unmarshaller if none exists for the specified
     * key.
     * 
     * @param unmarshallerKey
     *            : Class used to create an instance of Unmarshaller
     */
    @SuppressWarnings("rawtypes")
    @Override
    public final Object makeObject(final Object unmarshallerKey) {
        if (unmarshallerKey instanceof Class) {
            Class clazz = (Class) unmarshallerKey;
            // Retrieve or create a JACBContext for this key
            JAXBContext jc = JAXB_CONTEXT_MAP.get(unmarshallerKey);
            if (jc == null) {
                try {
                    jc = JAXBContext.newInstance(clazz);
                    // JAXB Context is threadsafe, it can be reused, so let's store it for later
                    JAXB_CONTEXT_MAP.put(unmarshallerKey, jc);
                } catch (JAXBException e) {
                    // Deal with that error here
                    return null;
                }
            }
            try {
                return jc.createUnmarshaller();
            } catch (JAXBException e) {
                // Deal with that error here
            }
        }
        return null;
    }

    @Override
    public final boolean validateObject(final Object key, final Object object) {
        return true;
    }
}
UnmarshallerPool.java
import org.apache.commons.pool.impl.GenericKeyedObjectPool;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class UnmarshallerPool extends GenericKeyedObjectPool {
    @Autowired
    public UnmarshallerPool(final UnmarshallerFactory unmarshallerFactory) {
    // Make usage of the factory created above
    super(unmarshallerFactory);
            // You'd better set the properties from a file here
    this.setMaxIdle(4);
    this.setMaxActive(5);
    this.setMinEvictableIdleTimeMillis(30000);
    this.setTestOnBorrow(false);
    this.setMaxWait(1000);
    }

    public UnmarshallerPool(UnmarshallerFactory objFactory,
        GenericKeyedObjectPool.Config config) {
        super(objFactory, config);
    }

    @Override
    public Object borrowObject(Object key) throws Exception {
        return super.borrowObject(key);
    }

    @Override
    public void returnObject(Object key, Object obj) throws Exception {
        super.returnObject(key, obj);
    }
}

在需要JAXB Unmarshaller的类(class)中:
    // Autowiring of the Pool
    @Resource(name = "unmarshallerPool")
    private UnmarshallerPool unmarshallerPool;

    public void myMethod() {
        Unmarshaller u = null;
        try {
            // Borrow an Unmarshaller from the pool
            u = (Unmarshaller) this.unmarshallerPool.borrowObject(MyJAXBClass.class);
            MyJAXBClass myJAXBObject = (MyJAXBClass) u.unmarshal(url);
            // Do whatever
        } catch (Exception e) {
            // Deal with that error
        } finally {
            try {
                // Return the Unmarshaller to the pool
                this.unmarshallerPool.returnObject(MyJAXBClass.class, u);
            } catch (Exception ignore) {
            }
        }
    }

这个示例很幼稚,因为它仅使用一个类来创建JAXBContext,并且使用与Keyed Pool的Key相同的Class实例。可以通过将一个类数组作为参数而不是仅一个类作为参数来进行改进。

希望这会有所帮助。

最佳答案

解码器的创建旨在减轻负担。我建议在制定池化策略之前进行一些分析。

关于spring - 创建一个JAXB Unmarshaller池,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5509638/

相关文章:

java - Spring 数据源返回 null

java - 您可以有多组 JAXB 注释来编码/解码为不同的 XML 吗?

delphi - Delphi 是否有通用的 "Object Pool"实现?

c++ - 如何防止在 boost::fast_pool_allocator 管理的对象上调用析构函数?

java - 使用 Spring Boot 提供 gzip 压缩文件

mysql - mysql 中的用户和行级别日志记录

jaxb - 使用 XmlElementWrapper 时编码集合

java - java中的字符串池

java - 使用 Struts2 和 hibernate 创建 Web 服务(SOAP 或 REST)

java - Jaxb 没有发现我的基类的正确儿子