空间换时间
- 在大型应用中为了提升效率,通常会把需要创建的对象提前创建出来,这就是所谓的空间换时间手段。比如jdbc的连接池,通常连接数据库等外部中间件时,需要经历对象的创建、TCP连接的建立等一系列动作之后,连接方能使用;
使用common pool2实现资源的池化
- 需要使用池的配置类GenericObjectPoolConfig来进行池的一些属性配置
- 实现接口PooledObjectFactory,创建一个作为池管理资源的工厂类
- 内建的池实现类GenericObjectPool,实例化该类时需要传入PooledObjectFactory的实现类以及池的配置类GenericObjectPoolConfig
实例,实现rabbitmq channel的池化
// 实现接口PooledObjectFactory
package com.luhc.pool;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConnectionFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.PooledObjectFactory;
import org.apache.commons.pool2.impl.DefaultPooledObject;
/**
* @author luhuancheng
* @since 2018/4/22 21:37
*/
public class MyRabbitMQChannelPoolFactory implements PooledObjectFactory<Channel> {
private ConnectionFactory factory;
public MyRabbitMQChannelPoolFactory(ConnectionFactory factory) {
this.factory = factory;
}
@Override
public PooledObject<Channel> makeObject() throws Exception {
// 池对象创建实例化资源
return new DefaultPooledObject<>(factory.newConnection().createChannel());
}
@Override
public void destroyObject(PooledObject<Channel> p) throws Exception {
// 池对象销毁资源
if (p != null) {
p.getObject().close();
}
}
@Override
public boolean validateObject(PooledObject<Channel> p) {
// 验证资源是否可用
return p.getObject().isOpen();
}
@Override
public void activateObject(PooledObject<Channel> p) throws Exception {
}
@Override
public void passivateObject(PooledObject<Channel> p) throws Exception {
}
}
// 自定义池
package com.luhc.pool;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConnectionFactory;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
/**
* @author luhuancheng
* @since 2018/4/22 21:41
*/
public class MyRabbitMQChannelPool {
private GenericObjectPool<Channel> pool;
public MyRabbitMQChannelPool(ConnectionFactory factory, GenericObjectPoolConfig poolConfig) {
this.pool = new GenericObjectPool<>(new MyRabbitMQChannelPoolFactory(factory), poolConfig);
}
public Channel getChannel() {
try {
return pool.borrowObject();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public void returnChannel(Channel channel) {
if (channel != null) {
pool.returnObject(channel);
}
}
}