306.6. 高级使用备注
306.6.1. 可插拔连接资源管理
SJMS 通过内置连接池提供 JMS 连接资源管理。 http://docs.oracle.com/javaee/5/api/javax/jms/Connection.html这消除了依赖第三方 API 池逻辑的需求。但是,您可能需要使用外部连接资源管理器,如 J2EE 或 OSGi 容器提供的资源管理器。对于此 SJMS 提供了一个接口,可用于覆盖内部 SJMS 连接池功能。这通过 ConnectionResource 接口来完成。
Connection Resource 提供了根据需要来浏览和返回连接方法,即用于向 SJMS 组件提供连接池的合同。如果需要将 SJMS 与外部连接池管理器集成时,应使用用户。
建议您为标准的 ConnectionFactory 提供程序使用通过 SJMS as-is 提供的 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 传递到 SjmsComponent :
CamelContext camelContext = new DefaultCamelContext();
AMQConnectionResource pool = new AMQConnectionResource("tcp://localhost:33333", 1);
SjmsComponent component = new SjmsComponent();
component.setConnectionResource(pool);
camelContext.addComponent("sjms", component);
要查看其使用的完整示例,请参阅 ConnectionResourceIT。