下面列出了怎么用org.apache.commons.pool2.impl.GenericKeyedObjectPool的API类实例代码及写法,或者点击链接到github查看源代码。
private synchronized GenericKeyedObjectPool<String, Script> getPool() {
if (pool == null) {
GenericKeyedObjectPoolConfig<Script> poolConfig = new GenericKeyedObjectPoolConfig<>();
poolConfig.setMaxTotalPerKey(-1);
poolConfig.setMaxIdlePerKey(globalConfig.getGroovyEvaluationPoolMaxIdle());
pool = new GenericKeyedObjectPool<>(
new BaseKeyedPooledObjectFactory<String, Script>() {
@Override
public Script create(String key) {
return createScript(key);
}
@Override
public PooledObject<Script> wrap(Script value) {
return new DefaultPooledObject<>(value);
}
},
poolConfig
);
}
return pool;
}
@Override
protected void doInitialize() throws Exception {
if (this.pooledObjectFactory == null) {
this.pooledObjectFactory = new ObjectFactory();
}
GenericKeyedObjectPool<String, Object> genericKeyedObjectPool = new GenericKeyedObjectPool<String, Object>(
pooledObjectFactory, config);
genericKeyedObjectPool.setTestOnBorrow(true);
genericKeyedObjectPool.setTestOnCreate(true);
genericKeyedObjectPool.setSoftMinEvictableIdleTimeMillis(DEFAULT_SOFT_MIN_EVICTABLE_IDLE_TIME_MILLIS);
genericKeyedObjectPool.setMinEvictableIdleTimeMillis(DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS);
genericKeyedObjectPool.setTimeBetweenEvictionRunsMillis(DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS);
this.objectPool = genericKeyedObjectPool;
}
public void initConnectionPool() throws Exception {
connPool = new GenericKeyedObjectPool<>(new CarreraConnectionFactory(config), config);
for (Node node : getAllNodes()) {
connPool.addObject(node);
}
initScheduler();
}
private GenericKeyedObjectPool<PreparedContextKey, PreparedContext> createPreparedContextPool() {
PreparedContextFactory factory = new PreparedContextFactory();
KylinConfig kylinConfig = getConfig();
GenericKeyedObjectPoolConfig config = new GenericKeyedObjectPoolConfig();
config.setMaxTotalPerKey(kylinConfig.getQueryMaxCacheStatementInstancePerKey());
config.setMaxTotal(kylinConfig.getQueryMaxCacheStatementNum());
config.setBlockWhenExhausted(false);
config.setMinEvictableIdleTimeMillis(10 * 60 * 1000L); // cached statement will be evict if idle for 10 minutes
config.setTimeBetweenEvictionRunsMillis(60 * 1000L);
GenericKeyedObjectPool<PreparedContextKey, PreparedContext> pool = new GenericKeyedObjectPool<>(factory,
config);
return pool;
}
public void initConnectionPool() throws Exception {
connPool = new GenericKeyedObjectPool<>(new CarreraConnectionFactory(config), config);
for (Node node : getAllNodes()) {
connPool.addObject(node);
}
initScheduler();
}
private void createGenericKeyedObjectPool() {
new GenericKeyedObjectPool<>(new BaseKeyedPooledObjectFactory<Object, Object>() {
@Override
public Object create(Object key) {
return key;
}
@Override
public PooledObject<Object> wrap(Object value) {
return new DefaultPooledObject<>(value);
}
});
}
public void init() {
debug = conf.getBoolean("literpc.endpoint.tcp.debug", false);
GenericKeyedObjectPoolConfig poolConfig = new GenericKeyedObjectPoolConfig();
poolConfig.setMaxTotal(500);
poolConfig.setTestWhileIdle(true);
pool = new GenericKeyedObjectPool<>(new RpcSocketFactory(), poolConfig);
}
@RequestMapping("/test/{productId}")
public Long test(@PathVariable final long productId) {
productProducer.sendMessage(productId);
Map<String,PooledConnectionFactory> pooledConnectionFactoryMap= ConnectionFactoryContainer.getAllPooledConnectionFactory();
for(Map.Entry<String,PooledConnectionFactory> entry:pooledConnectionFactoryMap.entrySet()) {
JimPooledConnectionFactory jimPooledConnectionFactory=(JimPooledConnectionFactory) entry.getValue();
//jimPooledConnectionFactory.setExpiryTimeout();
GenericKeyedObjectPool<ConnectionKey, ConnectionPool> jimConnectionsPool = ((JimPooledConnectionFactory) entry.getValue()).getJimConnectionsPool();
//jimConnectionsPool.
jimConnectionsPool.clearOldest();
//jimConnectionsPool.set
Map<String, List<DefaultPooledObjectInfo>> defStringListMap= jimConnectionsPool.listAllObjects();
for(Map.Entry<String,List<DefaultPooledObjectInfo>> entry1 : defStringListMap.entrySet()){
List<DefaultPooledObjectInfo> defaultPooledObjectInfos=entry1.getValue();
System.out.println("123");
for(DefaultPooledObjectInfo defaultPooledObjectInfo:defaultPooledObjectInfos){
//defaultPooledObjectInfo.
System.out.println("123");
//((ConnectionPool)defaultPooledObjectInfo.pooledObject.getObject()).connection;
}
}
//jimConnectionsPool.get
System.out.println("123");
//((ObjectDeque)((java.util.concurrent.ConcurrentHashMap.MapEntry)((java.util.concurrent.ConcurrentHashMap)jimConnectionsPool.poolMap).entrySet().toArray()[0]).getValue()).allObjects
}
return productId;
}
@Bean
public GenericKeyedObjectPool<ChannelSessionKey, Channel> getChannelPool(final SshConfig sshConfig) throws JSchException {
final GenericKeyedObjectPoolConfig genericKeyedObjectPoolConfig = new GenericKeyedObjectPoolConfig();
genericKeyedObjectPoolConfig.setMaxTotalPerKey(10);
genericKeyedObjectPoolConfig.setBlockWhenExhausted(true);
return new GenericKeyedObjectPool(new KeyedPooledJschChannelFactory(sshConfig.getJschBuilder().build()));
}
public CommonSshTestConfiguration() throws JSchException {
//TODO (Corey) generalize this so that %HOME% works
//TODO create duplicate set of keys without a passphrase for testing
builder = new JschBuilder(getKnownHostsFile(),
getPrivateKey());
channelPool = new GenericKeyedObjectPool(new KeyedPooledJschChannelFactory(builder.build()));
remoteSystemConnection = new RemoteSystemConnection("N9SFGLabTomcatAdmin",
/*"Passw0rd1"*/"===encryptedPassword===".toCharArray(),
"somehost0005",
22);
}
public CommonSshTestConfiguration() throws JSchException {
//TODO (Corey) generalize this so that %HOME% works
//TODO create duplicate set of keys without a passphrase for testing
builder = new JschBuilder(getKnownHostsFile(),
getPrivateKey());
channelPool = new GenericKeyedObjectPool(new KeyedPooledJschChannelFactory(builder.build()));
remoteSystemConnection = new RemoteSystemConnection("N9SFGLabTomcatAdmin",
/*"Passw0rd1"*/"===encryptMe===".toCharArray(),
"somehost0005",
22);
}
public final void setKeyPooConfig(int minIdlePerKey, long softMinEvictableIdleTimeMillis, long minEvictableIdleTimeMillis, long timeBetweenEvictionRunsMillis) {
if (objectPool instanceof GenericKeyedObjectPool) {
logger.info("[setKeyPooConfig]{}, {}, {}, {}", minIdlePerKey, softMinEvictableIdleTimeMillis, minEvictableIdleTimeMillis, timeBetweenEvictionRunsMillis);
GenericKeyedObjectPool genericKeyedObjectPool = (GenericKeyedObjectPool) objectPool;
genericKeyedObjectPool.setMinIdlePerKey(minIdlePerKey);
genericKeyedObjectPool.setSoftMinEvictableIdleTimeMillis(softMinEvictableIdleTimeMillis);
genericKeyedObjectPool.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
genericKeyedObjectPool.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
} else {
logger.warn("[setKeyPooConfig][not generickeyedobjectpool]");
}
}
public void startPool() {
pool = new GenericKeyedObjectPool<String, VMwareClient>(
new VMClientFactory());
((GenericKeyedObjectPool<String, VMwareClient>) pool)
.setMaxIdlePerKey(10);
((GenericKeyedObjectPool<String, VMwareClient>) pool).setMaxTotal(20);
((GenericKeyedObjectPool<String, VMwareClient>) pool)
.setMaxTotalPerKey(20);
((GenericKeyedObjectPool<String, VMwareClient>) pool)
.setTestOnBorrow(true);
}
private GenericKeyedObjectPool<PreparedContextKey, PreparedContext> createPreparedContextPool() {
PreparedContextFactory factory = new PreparedContextFactory();
KylinConfig kylinConfig = getConfig();
GenericKeyedObjectPoolConfig config = new GenericKeyedObjectPoolConfig();
config.setMaxTotalPerKey(kylinConfig.getQueryMaxCacheStatementInstancePerKey());
config.setMaxTotal(kylinConfig.getQueryMaxCacheStatementNum());
config.setBlockWhenExhausted(false);
config.setMinEvictableIdleTimeMillis(10 * 60 * 1000L); // cached statement will be evict if idle for 10 minutes
config.setTimeBetweenEvictionRunsMillis(60 * 1000L);
GenericKeyedObjectPool<PreparedContextKey, PreparedContext> pool = new GenericKeyedObjectPool<>(factory,
config);
return pool;
}
private List<Task> createTasks(final GenericKeyedObjectPool<Integer, Object> pool) {
final List<Task> tasks = new ArrayList<>();
for (int i = 0; i < 250; i++) {
tasks.add(new Task(pool, i));
}
return tasks;
}
@Before
public void setUp() {
final GenericKeyedObjectPoolConfig<TestObject> config = new GenericKeyedObjectPoolConfig<>();
config.setMaxTotal(3);
final KeyedPooledObjectFactory<String, TestObject> factory =
new TestKeyedObjectFactory();
@SuppressWarnings("resource")
final KeyedObjectPool<String, TestObject> innerPool =
new GenericKeyedObjectPool<>(
factory, config);
pool = new ProxiedKeyedObjectPool<>(innerPool, getproxySource());
}
private static void reconstructConnectionPool() {
connectionFactory = new ModbusSlaveConnectionFactoryImpl();
GenericKeyedObjectPool<ModbusSlaveEndpoint, ModbusSlaveConnection> genericKeyedObjectPool = new GenericKeyedObjectPool<>(
connectionFactory, poolConfig);
genericKeyedObjectPool.setSwallowedExceptionListener(new SwallowedExceptionListener() {
@Override
public void onSwallowException(Exception e) {
logger.error("Connection pool swallowed unexpected exception: {}", e.getMessage());
}
});
connectionPool = genericKeyedObjectPool;
}
private void registerPool(final String userName, final String password) throws NamingException, SQLException {
final ConnectionPoolDataSource cpds = testCPDS(userName, password);
// Create an object pool to contain our PooledConnections
factory = new KeyedCPDSConnectionFactory(cpds, getValidationQuery(), getValidationQueryTimeout(),
isRollbackAfterValidation());
factory.setMaxConnLifetimeMillis(getMaxConnLifetimeMillis());
final GenericKeyedObjectPoolConfig<PooledConnectionAndInfo> config = new GenericKeyedObjectPoolConfig<>();
config.setBlockWhenExhausted(getDefaultBlockWhenExhausted());
config.setEvictionPolicyClassName(getDefaultEvictionPolicyClassName());
config.setLifo(getDefaultLifo());
config.setMaxIdlePerKey(getDefaultMaxIdle());
config.setMaxTotal(getMaxTotal());
config.setMaxTotalPerKey(getDefaultMaxTotal());
config.setMaxWaitMillis(getDefaultMaxWaitMillis());
config.setMinEvictableIdleTimeMillis(getDefaultMinEvictableIdleTimeMillis());
config.setMinIdlePerKey(getDefaultMinIdle());
config.setNumTestsPerEvictionRun(getDefaultNumTestsPerEvictionRun());
config.setSoftMinEvictableIdleTimeMillis(getDefaultSoftMinEvictableIdleTimeMillis());
config.setTestOnCreate(getDefaultTestOnCreate());
config.setTestOnBorrow(getDefaultTestOnBorrow());
config.setTestOnReturn(getDefaultTestOnReturn());
config.setTestWhileIdle(getDefaultTestWhileIdle());
config.setTimeBetweenEvictionRunsMillis(getDefaultTimeBetweenEvictionRunsMillis());
final KeyedObjectPool<UserPassKey, PooledConnectionAndInfo> tmpPool = new GenericKeyedObjectPool<>(factory,
config);
factory.setPool(tmpPool);
pool = tmpPool;
}
/**
* Uses the configured XAConnectionFactory to create a {@link PoolableManagedConnection}. Throws
* <code>IllegalStateException</code> if the connection factory returns null. Also initializes the connection using
* configured initialization SQL (if provided) and sets up a prepared statement pool associated with the
* PoolableManagedConnection if statement pooling is enabled.
*/
@Override
public synchronized PooledObject<PoolableConnection> makeObject() throws Exception {
Connection conn = getConnectionFactory().createConnection();
if (conn == null) {
throw new IllegalStateException("Connection factory returned null from createConnection");
}
initializeConnection(conn);
if (getPoolStatements()) {
conn = new PoolingConnection(conn);
final GenericKeyedObjectPoolConfig<DelegatingPreparedStatement> config = new GenericKeyedObjectPoolConfig<>();
config.setMaxTotalPerKey(-1);
config.setBlockWhenExhausted(false);
config.setMaxWaitMillis(0);
config.setMaxIdlePerKey(1);
config.setMaxTotal(getMaxOpenPreparedStatements());
final ObjectName dataSourceJmxName = getDataSourceJmxName();
final long connIndex = getConnectionIndex().getAndIncrement();
if (dataSourceJmxName != null) {
final StringBuilder base = new StringBuilder(dataSourceJmxName.toString());
base.append(Constants.JMX_CONNECTION_BASE_EXT);
base.append(Long.toString(connIndex));
config.setJmxNameBase(base.toString());
config.setJmxNamePrefix(Constants.JMX_STATEMENT_POOL_PREFIX);
} else {
config.setJmxEnabled(false);
}
final KeyedObjectPool<PStmtKey, DelegatingPreparedStatement> stmtPool = new GenericKeyedObjectPool<>(
(PoolingConnection) conn, config);
((PoolingConnection) conn).setStatementPool(stmtPool);
((PoolingConnection) conn).setCacheState(getCacheState());
}
final PoolableManagedConnection pmc = new PoolableManagedConnection(transactionRegistry, conn, getPool(),
getDisconnectionSqlCodes(), isFastFailValidation());
pmc.setCacheState(getCacheState());
return new DefaultPooledObject<>(pmc);
}
/**
* JIRA: DBCP-442
*/
@Test
public void testNullValidationQuery() throws Exception {
final UserPassKey key = new UserPassKey("userName", "password");
final KeyedCPDSConnectionFactory factory =
new KeyedCPDSConnectionFactory(cpds, null, -1, false);
final GenericKeyedObjectPool<UserPassKey, PooledConnectionAndInfo> pool = new GenericKeyedObjectPool<>(factory);
factory.setPool(pool);
pool.setTestOnBorrow(true);
final PooledConnection pcon = pool.borrowObject(key).getPooledConnection();
final Connection con = pcon.getConnection();
con.close();
}
@BeforeEach
public void setUp() throws Exception {
con = new PoolingConnection(new TesterConnection("test", "test"));
final GenericKeyedObjectPoolConfig<DelegatingPreparedStatement> config = new GenericKeyedObjectPoolConfig<>();
config.setMaxTotalPerKey(-1);
config.setBlockWhenExhausted(false);
config.setMaxWaitMillis(0);
config.setMaxIdlePerKey(1);
config.setMaxTotal(1);
final KeyedObjectPool<PStmtKey, DelegatingPreparedStatement> stmtPool =
new GenericKeyedObjectPool<>(con, config);
con.setStatementPool(stmtPool);
}
/**
* DBCP-180 - things get more interesting with statement pooling.
*/
@Test
public void testGarbageCollectorCleanUp02() throws Exception {
ds.setPoolPreparedStatements(true);
ds.setAccessToUnderlyingConnectionAllowed(true);
final DelegatingConnection<?> conn = (DelegatingConnection<?>) ds.getConnection();
final PoolableConnection poolableConn = (PoolableConnection) conn.getDelegate();
final PoolingConnection poolingConn = (PoolingConnection) poolableConn.getDelegate();
@SuppressWarnings("unchecked")
final
GenericKeyedObjectPool<PStmtKey, DelegatingPreparedStatement> gkop =
(GenericKeyedObjectPool<PStmtKey, DelegatingPreparedStatement>) TesterUtils.getField(poolingConn, "pstmtPool");
Assertions.assertEquals(0, conn.getTrace().size());
Assertions.assertEquals(0, gkop.getNumActive());
createStatement(conn);
Assertions.assertEquals(1, conn.getTrace().size());
Assertions.assertEquals(1, gkop.getNumActive());
System.gc();
// Finalization happens in a separate thread. Give the test time for
// that to complete.
int count = 0;
while (count < 50 && gkop.getNumActive() > 0) {
Thread.sleep(100);
count++;
}
Assertions.assertEquals(0, gkop.getNumActive());
Assertions.assertEquals(0, conn.getTrace().size());
}
/**
* Creates a new pooling context source, setting up the DirContext object
* factory and generic keyed object pool.
*/
public PooledContextSource(PoolConfig poolConfig) {
this.dirContextPooledObjectFactory = new DirContextPooledObjectFactory();
if (poolConfig != null) {
this.poolConfig = poolConfig;
GenericKeyedObjectPoolConfig objectPoolConfig = getConfig(poolConfig);
this.keyedObjectPool =
new GenericKeyedObjectPool<Object,Object>(this.dirContextPooledObjectFactory, objectPoolConfig);
} else {
this.keyedObjectPool =
new GenericKeyedObjectPool<Object,Object>(this.dirContextPooledObjectFactory);
}
}
public void initConnectionsPool() {
if (this.connectionsPool == null) {
final GenericKeyedObjectPoolConfig<PooledConnection> poolConfig = new GenericKeyedObjectPoolConfig<>();
poolConfig.setJmxEnabled(false);
this.connectionsPool = new GenericKeyedObjectPool<PooledConnectionKey, PooledConnection>(
new KeyedPooledObjectFactory<PooledConnectionKey, PooledConnection>() {
@Override
public PooledObject<PooledConnection> makeObject(PooledConnectionKey connectionKey) throws Exception {
Connection delegate = createProviderConnection(connectionKey);
PooledConnection connection = createPooledConnection(delegate);
connection.setIdleTimeout(getConnectionIdleTimeout());
connection.setMaxSessionsPerConnection(getMaxSessionsPerConnection());
connection.setBlockIfSessionPoolIsFull(isBlockIfSessionPoolIsFull());
if (isBlockIfSessionPoolIsFull() && getBlockIfSessionPoolIsFullTimeout() > 0) {
connection.setBlockIfSessionPoolIsFullTimeout(getBlockIfSessionPoolIsFullTimeout());
}
connection.setUseAnonymousProducers(isUseAnonymousProducers());
connection.setExplicitProducerCacheSize(getExplicitProducerCacheSize());
LOG.trace("Created new connection: {}", connection);
JmsPoolConnectionFactory.this.mostRecentlyCreated.set(connection);
return new DefaultPooledObject<PooledConnection>(connection);
}
@Override
public void destroyObject(PooledConnectionKey connectionKey, PooledObject<PooledConnection> pooledObject) throws Exception {
PooledConnection connection = pooledObject.getObject();
try {
LOG.trace("Destroying connection: {}", connection);
connection.close();
} catch (Exception e) {
LOG.warn("Close connection failed for connection: " + connection + ". This exception will be ignored.",e);
}
}
@Override
public boolean validateObject(PooledConnectionKey connectionKey, PooledObject<PooledConnection> pooledObject) {
PooledConnection connection = pooledObject.getObject();
if (connection != null && connection.expiredCheck()) {
LOG.trace("Connection has expired: {} and will be destroyed", connection);
return false;
}
return true;
}
@Override
public void activateObject(PooledConnectionKey connectionKey, PooledObject<PooledConnection> pooledObject) throws Exception {
}
@Override
public void passivateObject(PooledConnectionKey connectionKey, PooledObject<PooledConnection> pooledObject) throws Exception {
}
}, poolConfig);
// Set max idle (not max active) since our connections always idle in the pool.
this.connectionsPool.setMaxIdlePerKey(DEFAULT_MAX_CONNECTIONS);
this.connectionsPool.setLifo(false);
this.connectionsPool.setMinIdlePerKey(1);
this.connectionsPool.setBlockWhenExhausted(false);
// We always want our validate method to control when idle objects are evicted.
this.connectionsPool.setTestOnBorrow(true);
this.connectionsPool.setTestWhileIdle(true);
}
}
/**
* 启动连接池
*
* @throws Exception
*/
public void start() throws Exception {
LOG.info("Starting transport pool: " + poolConfig);
this.pool = new GenericKeyedObjectPool<ServiceInstance<RpcPayload>, TTransport>(
this, this.poolConfig);
}
public GenericKeyedObjectPool<ConnectionKey, ConnectionPool> getJimConnectionsPool() {
return jimConnectionsPool;
}
@Bean
public GenericKeyedObjectPool getGenericKeyedObjectPool(final JSch jsch) throws JSchException {
return new GenericKeyedObjectPool(new KeyedPooledJschChannelFactory(jsch));
}
public GenericKeyedObjectPool<ChannelSessionKey, Channel> getChannelPool() {
return channelPool;
}
public GenericKeyedObjectPool<ChannelSessionKey, Channel> getChannelPool() {
return channelPool;
}
@Bean
public static GenericKeyedObjectPool<ChannelSessionKey, Channel> getMockPool() {
return mockPool;
}