org.cg.eventbus.producer.PooledEventProducerFactory Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of org.cg.eventbus Show documentation
Show all versions of org.cg.eventbus Show documentation
Simplified messaging programming model with kafka implementation.
/**
*
*/
package org.cg.eventbus.producer;
import java.lang.reflect.Constructor;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.apache.log4j.Logger;
/**
* @author yanlinwang, liang.li
*
*/
public class PooledEventProducerFactory extends BasePooledObjectFactory< AbstractEventProducer> {
private static final Logger logger = Logger.getLogger(PooledEventProducerFactory.class);
private Configuration producerConf;
private AtomicInteger count = new AtomicInteger(0);
private Class extends AbstractEventProducer> poolType;
private Constructor pooledConstructor;
public PooledEventProducerFactory (Class extends AbstractEventProducer> poolType, String fileName)
throws ConfigurationException {
this(poolType,new PropertiesConfiguration(fileName));
}
public PooledEventProducerFactory (Class extends AbstractEventProducer> poolType, Configuration config) {
this.poolType = poolType;
producerConf = config;
try {
pooledConstructor = poolType.getConstructor(Configuration.class);
} catch (Exception e) {
logger.error("failed to get pooled object constructor", e);
}
}
@Override
public AbstractEventProducer create() throws Exception {
AbstractEventProducer producer = ( AbstractEventProducer ) pooledConstructor.newInstance(new Object[]{producerConf});
logger.info("Number of producer created " + count.addAndGet(1));
return producer;
}
@Override
public PooledObject> wrap(
AbstractEventProducer provider) {
return new DefaultPooledObject>(provider);
}
@Override
public void destroyObject(PooledObject> p) {
p.getObject().close();
}
}