305.5. 高级使用备注

305.5.1. 可插拔连接资源管理

SJMS2 通过内置连接池提供 JMS 连接资源管理。 http://docs.oracle.com/javaee/5/api/javax/jms/Connection.html这消除了依赖第三方 API 池逻辑的需求。但是,您可能需要使用外部连接资源管理器,如 J2EE 或 OSGi 容器提供的资源管理器。对于此 SJMS2,提供了一个接口,可用于覆盖内部 SJMS2 连接池功能。这通过 ConnectionResource 接口来完成。

Connection Resource 提供了根据需要来浏览和返回连接方法,即用于向 SJMS2 组件提供连接池的合同。如果需要将 SJMS2 与外部连接池管理器集成时,应使用用户。

建议您为标准的 ConnectionFactory 提供程序使用通过 SJMS2 作为原样提供的 ConnectionFactoryResource 实施,或者根据该组件优化的扩展。

以下是将插件的 ConnectionResource 和 ActiveMQ PooledConnectionFactory 搭配使用的示例:

public class AMQConnectionResource implements ConnectionResource {
    private PooledConnectionFactory pcf;

    public AMQConnectionResource(String connectString, int maxConnections) {
        super();
        pcf = new PooledConnectionFactory(connectString);
        pcf.setMaxConnections(maxConnections);
        pcf.start();
    }

    public void stop() {
        pcf.stop();
    }

    @Override
    public Connection borrowConnection() throws Exception {
        Connection answer = pcf.createConnection();
        answer.start();
        return answer;
    }

    @Override
    public Connection borrowConnection(long timeout) throws Exception {
        // SNIPPED...
    }

    @Override
    public void returnConnection(Connection connection) throws Exception {
        // Do nothing since there isn't a way to return a Connection
        // to the instance of PooledConnectionFactory
        log.info("Connection returned");
    }
}

然后,将 ConnectionResource 传递到 Sjms2Component

CamelContext camelContext = new DefaultCamelContext();
AMQConnectionResource pool = new AMQConnectionResource("tcp://localhost:33333", 1);
Sjms2Component component = new Sjms2Component();
component.setConnectionResource(pool);
camelContext.addComponent("sjms2", component);

要查看其使用的完整示例,请参阅 ConnectionResourceIT