List of usage examples for org.apache.commons.pool2.impl GenericObjectPoolConfig setTestOnBorrow
public void setTestOnBorrow(boolean testOnBorrow)
From source file:org.apache.dubbo.registry.redis.RedisRegistry.java
public RedisRegistry(URL url) { super(url);/* w w w . j a v a 2 s . c o m*/ if (url.isAnyHost()) { throw new IllegalStateException("registry address == null"); } GenericObjectPoolConfig config = new GenericObjectPoolConfig(); config.setTestOnBorrow(url.getParameter("test.on.borrow", true)); config.setTestOnReturn(url.getParameter("test.on.return", false)); config.setTestWhileIdle(url.getParameter("test.while.idle", false)); if (url.getParameter("max.idle", 0) > 0) config.setMaxIdle(url.getParameter("max.idle", 0)); if (url.getParameter("min.idle", 0) > 0) config.setMinIdle(url.getParameter("min.idle", 0)); if (url.getParameter("max.active", 0) > 0) config.setMaxTotal(url.getParameter("max.active", 0)); if (url.getParameter("max.total", 0) > 0) config.setMaxTotal(url.getParameter("max.total", 0)); if (url.getParameter("max.wait", url.getParameter("timeout", 0)) > 0) config.setMaxWaitMillis(url.getParameter("max.wait", url.getParameter("timeout", 0))); if (url.getParameter("num.tests.per.eviction.run", 0) > 0) config.setNumTestsPerEvictionRun(url.getParameter("num.tests.per.eviction.run", 0)); if (url.getParameter("time.between.eviction.runs.millis", 0) > 0) config.setTimeBetweenEvictionRunsMillis(url.getParameter("time.between.eviction.runs.millis", 0)); if (url.getParameter("min.evictable.idle.time.millis", 0) > 0) config.setMinEvictableIdleTimeMillis(url.getParameter("min.evictable.idle.time.millis", 0)); String cluster = url.getParameter("cluster", "failover"); if (!"failover".equals(cluster) && !"replicate".equals(cluster)) { throw new IllegalArgumentException("Unsupported redis cluster: " + cluster + ". The redis cluster only supported failover or replicate."); } replicate = "replicate".equals(cluster); List<String> addresses = new ArrayList<String>(); addresses.add(url.getAddress()); String[] backups = url.getParameter(Constants.BACKUP_KEY, new String[0]); if (backups != null && backups.length > 0) { addresses.addAll(Arrays.asList(backups)); } String password = url.getPassword(); for (String address : addresses) { int i = address.indexOf(':'); String host; int port; if (i > 0) { host = address.substring(0, i); port = Integer.parseInt(address.substring(i + 1)); } else { host = address; port = DEFAULT_REDIS_PORT; } if (StringUtils.isEmpty(password)) { this.jedisPools.put(address, new JedisPool(config, host, port, url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT), null, url.getParameter("db.index", 0))); } else { this.jedisPools.put(address, new JedisPool(config, host, port, url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT), password, url.getParameter("db.index", 0))); } } this.reconnectPeriod = url.getParameter(Constants.REGISTRY_RECONNECT_PERIOD_KEY, Constants.DEFAULT_REGISTRY_RECONNECT_PERIOD); String group = url.getParameter(Constants.GROUP_KEY, DEFAULT_ROOT); if (!group.startsWith(Constants.PATH_SEPARATOR)) { group = Constants.PATH_SEPARATOR + group; } if (!group.endsWith(Constants.PATH_SEPARATOR)) { group = group + Constants.PATH_SEPARATOR; } this.root = group; this.expirePeriod = url.getParameter(Constants.SESSION_TIMEOUT_KEY, Constants.DEFAULT_SESSION_TIMEOUT); this.expireFuture = expireExecutor.scheduleWithFixedDelay(new Runnable() { @Override public void run() { try { deferExpired(); // Extend the expiration time } catch (Throwable t) { // Defensive fault tolerance logger.error("Unexpected exception occur at defer expire time, cause: " + t.getMessage(), t); } } }, expirePeriod / 2, expirePeriod / 2, TimeUnit.MILLISECONDS); }
From source file:org.apache.dubbo.rpc.protocol.redis.RedisProtocol.java
@Override public <T> Invoker<T> refer(final Class<T> type, final URL url) throws RpcException { try {/*from w w w.j a v a 2 s . c o m*/ GenericObjectPoolConfig config = new GenericObjectPoolConfig(); config.setTestOnBorrow(url.getParameter("test.on.borrow", true)); config.setTestOnReturn(url.getParameter("test.on.return", false)); config.setTestWhileIdle(url.getParameter("test.while.idle", false)); if (url.getParameter("max.idle", 0) > 0) config.setMaxIdle(url.getParameter("max.idle", 0)); if (url.getParameter("min.idle", 0) > 0) config.setMinIdle(url.getParameter("min.idle", 0)); if (url.getParameter("max.active", 0) > 0) config.setMaxTotal(url.getParameter("max.active", 0)); if (url.getParameter("max.total", 0) > 0) config.setMaxTotal(url.getParameter("max.total", 0)); if (url.getParameter("max.wait", 0) > 0) config.setMaxWaitMillis(url.getParameter("max.wait", 0)); if (url.getParameter("num.tests.per.eviction.run", 0) > 0) config.setNumTestsPerEvictionRun(url.getParameter("num.tests.per.eviction.run", 0)); if (url.getParameter("time.between.eviction.runs.millis", 0) > 0) config.setTimeBetweenEvictionRunsMillis(url.getParameter("time.between.eviction.runs.millis", 0)); if (url.getParameter("min.evictable.idle.time.millis", 0) > 0) config.setMinEvictableIdleTimeMillis(url.getParameter("min.evictable.idle.time.millis", 0)); final JedisPool jedisPool = new JedisPool(config, url.getHost(), url.getPort(DEFAULT_PORT), url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT)); final int expiry = url.getParameter("expiry", 0); final String get = url.getParameter("get", "get"); final String set = url.getParameter("set", Map.class.equals(type) ? "put" : "set"); final String delete = url.getParameter("delete", Map.class.equals(type) ? "remove" : "delete"); return new AbstractInvoker<T>(type, url) { @Override protected Result doInvoke(Invocation invocation) throws Throwable { Jedis jedis = null; try { jedis = jedisPool.getResource(); if (get.equals(invocation.getMethodName())) { if (invocation.getArguments().length != 1) { throw new IllegalArgumentException( "The redis get method arguments mismatch, must only one arguments. interface: " + type.getName() + ", method: " + invocation.getMethodName() + ", url: " + url); } byte[] value = jedis.get(String.valueOf(invocation.getArguments()[0]).getBytes()); if (value == null) { return new RpcResult(); } ObjectInput oin = getSerialization(url).deserialize(url, new ByteArrayInputStream(value)); return new RpcResult(oin.readObject()); } else if (set.equals(invocation.getMethodName())) { if (invocation.getArguments().length != 2) { throw new IllegalArgumentException( "The redis set method arguments mismatch, must be two arguments. interface: " + type.getName() + ", method: " + invocation.getMethodName() + ", url: " + url); } byte[] key = String.valueOf(invocation.getArguments()[0]).getBytes(); ByteArrayOutputStream output = new ByteArrayOutputStream(); ObjectOutput value = getSerialization(url).serialize(url, output); value.writeObject(invocation.getArguments()[1]); jedis.set(key, output.toByteArray()); if (expiry > 1000) { jedis.expire(key, expiry / 1000); } return new RpcResult(); } else if (delete.equals(invocation.getMethodName())) { if (invocation.getArguments().length != 1) { throw new IllegalArgumentException( "The redis delete method arguments mismatch, must only one arguments. interface: " + type.getName() + ", method: " + invocation.getMethodName() + ", url: " + url); } jedis.del(String.valueOf(invocation.getArguments()[0]).getBytes()); return new RpcResult(); } else { throw new UnsupportedOperationException( "Unsupported method " + invocation.getMethodName() + " in redis service."); } } catch (Throwable t) { RpcException re = new RpcException("Failed to invoke redis service method. interface: " + type.getName() + ", method: " + invocation.getMethodName() + ", url: " + url + ", cause: " + t.getMessage(), t); if (t instanceof TimeoutException || t instanceof SocketTimeoutException) { re.setCode(RpcException.TIMEOUT_EXCEPTION); } else if (t instanceof JedisConnectionException || t instanceof IOException) { re.setCode(RpcException.NETWORK_EXCEPTION); } else if (t instanceof JedisDataException) { re.setCode(RpcException.SERIALIZATION_EXCEPTION); } throw re; } finally { if (jedis != null) { try { jedis.close(); } catch (Throwable t) { logger.warn("returnResource error: " + t.getMessage(), t); } } } } @Override public void destroy() { super.destroy(); try { jedisPool.destroy(); } catch (Throwable e) { logger.warn(e.getMessage(), e); } } }; } catch (Throwable t) { throw new RpcException("Failed to refer redis service. interface: " + type.getName() + ", url: " + url + ", cause: " + t.getMessage(), t); } }
From source file:org.apache.ofbiz.entity.connection.DBCPConnectionFactory.java
public Connection getConnection(GenericHelperInfo helperInfo, JdbcElement abstractJdbc) throws SQLException, GenericEntityException { String cacheKey = helperInfo.getHelperFullName(); DebugManagedDataSource mds = dsCache.get(cacheKey); if (mds != null) { return TransactionUtil.getCursorConnection(helperInfo, mds.getConnection()); }// ww w. j a v a 2s . c om if (!(abstractJdbc instanceof InlineJdbc)) { throw new GenericEntityConfException( "DBCP requires an <inline-jdbc> child element in the <datasource> element"); } InlineJdbc jdbcElement = (InlineJdbc) abstractJdbc; // connection properties TransactionManager txMgr = TransactionFactoryLoader.getInstance().getTransactionManager(); String driverName = jdbcElement.getJdbcDriver(); String jdbcUri = helperInfo.getOverrideJdbcUri(jdbcElement.getJdbcUri()); String jdbcUsername = helperInfo.getOverrideUsername(jdbcElement.getJdbcUsername()); String jdbcPassword = helperInfo.getOverridePassword(EntityConfig.getJdbcPassword(jdbcElement)); // pool settings int maxSize = jdbcElement.getPoolMaxsize(); int minSize = jdbcElement.getPoolMinsize(); int maxIdle = jdbcElement.getIdleMaxsize(); // maxIdle must be greater than pool-minsize maxIdle = maxIdle > minSize ? maxIdle : minSize; // load the driver Driver jdbcDriver; synchronized (DBCPConnectionFactory.class) { // Sync needed for MS SQL JDBC driver. See OFBIZ-5216. try { jdbcDriver = (Driver) Class .forName(driverName, true, Thread.currentThread().getContextClassLoader()).newInstance(); } catch (Exception e) { Debug.logError(e, module); throw new GenericEntityException(e.getMessage(), e); } } // connection factory properties Properties cfProps = new Properties(); cfProps.put("user", jdbcUsername); cfProps.put("password", jdbcPassword); // create the connection factory org.apache.commons.dbcp2.ConnectionFactory cf = new DriverConnectionFactory(jdbcDriver, jdbcUri, cfProps); // wrap it with a LocalXAConnectionFactory XAConnectionFactory xacf = new LocalXAConnectionFactory(txMgr, cf); // create the pool object factory PoolableConnectionFactory factory = new PoolableManagedConnectionFactory(xacf, null); factory.setValidationQuery(jdbcElement.getPoolJdbcTestStmt()); factory.setDefaultReadOnly(false); factory.setRollbackOnReturn(false); factory.setEnableAutoCommitOnReturn(false); String transIso = jdbcElement.getIsolationLevel(); if (!transIso.isEmpty()) { if ("Serializable".equals(transIso)) { factory.setDefaultTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE); } else if ("RepeatableRead".equals(transIso)) { factory.setDefaultTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ); } else if ("ReadUncommitted".equals(transIso)) { factory.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED); } else if ("ReadCommitted".equals(transIso)) { factory.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); } else if ("None".equals(transIso)) { factory.setDefaultTransactionIsolation(Connection.TRANSACTION_NONE); } } // configure the pool settings GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig(); poolConfig.setMaxTotal(maxSize); // settings for idle connections poolConfig.setMaxIdle(maxIdle); poolConfig.setMinIdle(minSize); poolConfig.setTimeBetweenEvictionRunsMillis(jdbcElement.getTimeBetweenEvictionRunsMillis()); poolConfig.setMinEvictableIdleTimeMillis(-1); // disabled in favour of setSoftMinEvictableIdleTimeMillis(...) poolConfig.setSoftMinEvictableIdleTimeMillis(jdbcElement.getSoftMinEvictableIdleTimeMillis()); poolConfig.setNumTestsPerEvictionRun(maxSize); // test all the idle connections // settings for when the pool is exhausted poolConfig.setBlockWhenExhausted(true); // the thread requesting the connection waits if no connection is available poolConfig.setMaxWaitMillis(jdbcElement.getPoolSleeptime()); // throw an exception if, after getPoolSleeptime() ms, no connection is available for the requesting thread // settings for the execution of the validation query poolConfig.setTestOnCreate(jdbcElement.getTestOnCreate()); poolConfig.setTestOnBorrow(jdbcElement.getTestOnBorrow()); poolConfig.setTestOnReturn(jdbcElement.getTestOnReturn()); poolConfig.setTestWhileIdle(jdbcElement.getTestWhileIdle()); GenericObjectPool<PoolableConnection> pool = new GenericObjectPool<PoolableConnection>(factory, poolConfig); factory.setPool(pool); mds = new DebugManagedDataSource(pool, xacf.getTransactionRegistry()); mds.setAccessToUnderlyingConnectionAllowed(true); // cache the pool dsCache.putIfAbsent(cacheKey, mds); mds = dsCache.get(cacheKey); return TransactionUtil.getCursorConnection(helperInfo, mds.getConnection()); }
From source file:org.bigbluebutton.common2.redis.RedisAwareCommunicator.java
protected GenericObjectPoolConfig createPoolingConfig() { GenericObjectPoolConfig config = new GenericObjectPoolConfig(); config.setMaxTotal(32);//from w ww. ja v a 2s . co m config.setMaxIdle(8); config.setMinIdle(1); config.setTestOnBorrow(true); config.setTestOnReturn(true); config.setTestWhileIdle(true); config.setNumTestsPerEvictionRun(12); config.setMaxWaitMillis(5000); config.setTimeBetweenEvictionRunsMillis(60000); config.setBlockWhenExhausted(true); return config; }
From source file:org.bigbluebutton.core.service.recorder.RedisDispatcher.java
public RedisDispatcher(String host, int port, String password, int keysExpiresInSec) { GenericObjectPoolConfig config = new GenericObjectPoolConfig(); config.setMaxTotal(32);//from ww w . j av a2 s. co m config.setMaxIdle(8); config.setMinIdle(1); config.setTestOnBorrow(true); config.setTestOnReturn(true); config.setTestWhileIdle(true); config.setNumTestsPerEvictionRun(12); config.setMaxWaitMillis(5000); config.setTimeBetweenEvictionRunsMillis(60000); config.setBlockWhenExhausted(true); this.keysExpiresInSec = keysExpiresInSec; // Set the name of this client to be able to distinguish when doing // CLIENT LIST on redis-cli redisPool = new JedisPool(config, host, port, Protocol.DEFAULT_TIMEOUT, null, Protocol.DEFAULT_DATABASE, "BbbAppsAkkaRec"); }
From source file:org.cloudgraph.hbase.connect.HBaseConnectionManager.java
private HBaseConnectionManager() { this.config = CloudGraphContext.instance().getConfig(); GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig(); poolConfig.setMaxTotal(//from w w w . ja v a2 s . co m this.config.getInt(CONNECTION_POOL_MAX_TOTAL, GenericObjectPoolConfig.DEFAULT_MAX_TOTAL)); if (this.config.get(CONNECTION_POOL_MAX_SIZE) != null) poolConfig.setMaxTotal( this.config.getInt(CONNECTION_POOL_MAX_SIZE, GenericObjectPoolConfig.DEFAULT_MAX_TOTAL)); poolConfig .setMaxIdle(this.config.getInt(CONNECTION_POOL_MAX_IDLE, GenericObjectPoolConfig.DEFAULT_MAX_IDLE)); poolConfig .setMinIdle(this.config.getInt(CONNECTION_POOL_MIN_IDLE, GenericObjectPoolConfig.DEFAULT_MIN_IDLE)); if (this.config.get(CONNECTION_POOL_MIN_SIZE) != null) poolConfig.setMinIdle( this.config.getInt(CONNECTION_POOL_MIN_SIZE, GenericObjectPoolConfig.DEFAULT_MIN_IDLE)); poolConfig.setLifo(this.config.getBoolean(CONNECTION_POOL_LIFO, GenericObjectPoolConfig.DEFAULT_LIFO)); poolConfig.setMaxWaitMillis(this.config.getLong(CONNECTION_POOL_MAX_WAIT_MILLIS, GenericObjectPoolConfig.DEFAULT_MAX_WAIT_MILLIS)); // eviction poolConfig.setTimeBetweenEvictionRunsMillis( this.config.getLong(CONNECTION_POOL_TIME_BETWEEN_EVICTION_RUNS_MILLIS, GenericObjectPoolConfig.DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS)); poolConfig.setEvictionPolicyClassName(this.config.get(CONNECTION_POOL_EVICTION_POLICY_CLASS_NAME, GenericObjectPoolConfig.DEFAULT_EVICTION_POLICY_CLASS_NAME)); poolConfig.setMinEvictableIdleTimeMillis(this.config.getLong(CONNECTION_POOL_MIN_EVICTABLE_IDLE_TIME_MILLIS, GenericObjectPoolConfig.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS)); poolConfig.setSoftMinEvictableIdleTimeMillis( this.config.getLong(CONNECTION_POOL_SOFT_MIN_EVICTABLE_IDLE_TIME_MILLIS, GenericObjectPoolConfig.DEFAULT_SOFT_MIN_EVICTABLE_IDLE_TIME_MILLIS)); poolConfig.setNumTestsPerEvictionRun(this.config.getInt(CONNECTION_POOL_NUM_TESTS_PER_EVICTION_RUN, GenericObjectPoolConfig.DEFAULT_NUM_TESTS_PER_EVICTION_RUN)); poolConfig.setTestOnCreate(this.config.getBoolean(CONNECTION_POOL_TEST_ON_CREATE, GenericObjectPoolConfig.DEFAULT_TEST_ON_CREATE)); poolConfig.setTestOnBorrow(this.config.getBoolean(CONNECTION_POOL_TEST_ON_BORROW, GenericObjectPoolConfig.DEFAULT_TEST_ON_BORROW)); poolConfig.setTestOnReturn(this.config.getBoolean(CONNECTION_POOL_TEST_ON_RETURN, GenericObjectPoolConfig.DEFAULT_TEST_ON_RETURN)); poolConfig.setTestWhileIdle(this.config.getBoolean(CONNECTION_POOL_TEST_WHILE_IDLE, GenericObjectPoolConfig.DEFAULT_TEST_WHILE_IDLE)); poolConfig.setBlockWhenExhausted(this.config.getBoolean(CONNECTION_POOL_BLOCK_WHEN_EXHAUSTED, GenericObjectPoolConfig.DEFAULT_BLOCK_WHEN_EXHAUSTED)); poolConfig.setJmxEnabled(this.config.getBoolean(CONNECTION_POOL_JMX_ENABLED, false)); poolConfig.setJmxNameBase( this.config.get(CONNECTION_POOL_JMX_NAME_BASE, GenericObjectPoolConfig.DEFAULT_JMX_NAME_BASE)); poolConfig.setJmxNamePrefix( this.config.get(CONNECTION_POOL_JMX_NAME_PREFIX, GenericObjectPoolConfig.DEFAULT_JMX_NAME_PREFIX)); PooledConnectionFactory factory = new PooledConnectionFactory(this.config); this.pool = new GenericObjectPool<Connection>(factory, poolConfig); factory.setPool(pool); log.info("created connection pool[ " + "\n\tMaxTotal:\t\t" + poolConfig.getMaxTotal() + "\n\tMinIdle:\t\t" + poolConfig.getMinIdle() + "\n\tMaxIdle:\t\t" + poolConfig.getMaxIdle() + "\n\tLifo:\t\t" + poolConfig.getLifo() + "\n\tMaxWaitMillis:\t\t" + poolConfig.getMaxWaitMillis() + "\n\tTimeBetweenEvictionRunsMillis:\t\t" + poolConfig.getTimeBetweenEvictionRunsMillis() + "\n\tEvictionPolicyClassName:\t\t" + poolConfig.getEvictionPolicyClassName() + "\n\tMinEvictableIdleTimeMillis:\t\t" + poolConfig.getMinEvictableIdleTimeMillis() + "\n\tSoftMinEvictableIdleTimeMillis:\t\t" + poolConfig.getSoftMinEvictableIdleTimeMillis() + "\n\tNumTestsPerEvictionRun:\t\t" + poolConfig.getNumTestsPerEvictionRun() + "\n...]"); }
From source file:org.eclipse.kapua.broker.core.pool.JmsAssistantProducerPool.java
/** * Create a JmsAssistantProducerPool from the given factory * /*w w w. j a va 2 s. c om*/ * @param factory */ protected JmsAssistantProducerPool(JmsAssistantProducerWrapperFactory factory) { super(factory); // TODO parameter to be added to configuration // int totalMaxSize = KapuaEnvironmentConfig.getInstance().getString(KapuaEnvironmentConfigKeys.POOL_TOTAL_MAX_SIZE); // int maxSize = KapuaEnvironmentConfig.getInstance().getString(KapuaEnvironmentConfigKeys.POOL_MAX_SIZE); // int minSize = KapuaEnvironmentConfig.getInstance().getString(KapuaEnvironmentConfigKeys.POOL_MIN_SIZE); int totalMaxSize = 25; int maxSize = 25; int minSize = 10; GenericObjectPoolConfig jmsPoolConfig = new GenericObjectPoolConfig(); jmsPoolConfig.setMaxTotal(totalMaxSize); jmsPoolConfig.setMaxIdle(maxSize); jmsPoolConfig.setMinIdle(minSize); s_logger.info("Set test on return to true for JmsAssistantProducerPool"); jmsPoolConfig.setTestOnReturn(true); s_logger.info("Set test on borrow to true for JmsAssistantProducerPool"); jmsPoolConfig.setTestOnBorrow(true); s_logger.info("Set block when exausted to true for JmsAssistantProducerPool"); jmsPoolConfig.setBlockWhenExhausted(true); setConfig(jmsPoolConfig); }
From source file:org.eclipse.kapua.transport.mqtt.pooling.MqttClientPool.java
/** * Initialize a {@link MqttClientPool} with the according configuration sourced from {@link MqttClientPoolSetting}. * //from w w w . j ava 2s. co m * @since 1.0.0 */ private MqttClientPool(PooledMqttClientFactory factory) { super(factory); MqttClientPoolSetting config = MqttClientPoolSetting.getInstance(); GenericObjectPoolConfig clientPoolConfig = new GenericObjectPoolConfig(); clientPoolConfig.setMinIdle(config.getInt(MqttClientPoolSettingKeys.CLIENT_POOL_SIZE_IDLE_MIN)); clientPoolConfig.setMaxIdle(config.getInt(MqttClientPoolSettingKeys.CLIENT_POOL_SIZE_IDLE_MAX)); clientPoolConfig.setMaxTotal(config.getInt(MqttClientPoolSettingKeys.CLIENT_POOL_SIZE_TOTAL_MAX)); clientPoolConfig.setMaxWaitMillis(config.getInt(MqttClientPoolSettingKeys.CLIENT_POOL_BORROW_WAIT_MAX)); clientPoolConfig.setTestOnReturn(config.getBoolean(MqttClientPoolSettingKeys.CLIENT_POOL_ON_RETURN_TEST)); clientPoolConfig.setTestOnBorrow(config.getBoolean(MqttClientPoolSettingKeys.CLIENT_POOL_ON_BORROW_TEST)); clientPoolConfig.setTestWhileIdle(config.getBoolean(MqttClientPoolSettingKeys.CLIENT_POOL_WHEN_IDLE_TEST)); clientPoolConfig.setBlockWhenExhausted( config.getBoolean(MqttClientPoolSettingKeys.CLIENT_POOL_WHEN_EXAUSTED_BLOCK)); clientPoolConfig.setTimeBetweenEvictionRunsMillis( config.getLong(MqttClientPoolSettingKeys.CLIENT_POOL_EVICTION_INTERVAL)); setConfig(clientPoolConfig); }
From source file:org.jooby.jedis.Redis.java
private GenericObjectPoolConfig poolConfig(final Config config) { GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig(); poolConfig.setBlockWhenExhausted(config.getBoolean("blockWhenExhausted")); poolConfig.setEvictionPolicyClassName(config.getString("evictionPolicyClassName")); poolConfig.setJmxEnabled(config.getBoolean("jmxEnabled")); poolConfig.setJmxNamePrefix(config.getString("jmxNamePrefix")); poolConfig.setLifo(config.getBoolean("lifo")); poolConfig.setMaxIdle(config.getInt("maxIdle")); poolConfig.setMaxTotal(config.getInt("maxTotal")); poolConfig.setMaxWaitMillis(config.getDuration("maxWait", TimeUnit.MILLISECONDS)); poolConfig.setMinEvictableIdleTimeMillis(config.getDuration("minEvictableIdle", TimeUnit.MILLISECONDS)); poolConfig.setMinIdle(config.getInt("minIdle")); poolConfig.setNumTestsPerEvictionRun(config.getInt("numTestsPerEvictionRun")); poolConfig.setSoftMinEvictableIdleTimeMillis( config.getDuration("softMinEvictableIdle", TimeUnit.MILLISECONDS)); poolConfig.setTestOnBorrow(config.getBoolean("testOnBorrow")); poolConfig.setTestOnReturn(config.getBoolean("testOnReturn")); poolConfig.setTestWhileIdle(config.getBoolean("testWhileIdle")); poolConfig.setTimeBetweenEvictionRunsMillis( config.getDuration("timeBetweenEvictionRuns", TimeUnit.MILLISECONDS)); return poolConfig; }
From source file:org.noerp.entity.connection.DBCPConnectionFactory.java
public Connection getConnection(GenericHelperInfo helperInfo, JdbcElement abstractJdbc) throws SQLException, GenericEntityException { String cacheKey = helperInfo.getHelperFullName(); ManagedDataSource mds = dsCache.get(cacheKey); if (mds != null) { return TransactionUtil.getCursorConnection(helperInfo, mds.getConnection()); }// ww w . j a v a2 s . c o m if (!(abstractJdbc instanceof InlineJdbc)) { throw new GenericEntityConfException( "DBCP requires an <inline-jdbc> child element in the <datasource> element"); } InlineJdbc jdbcElement = (InlineJdbc) abstractJdbc; // connection properties TransactionManager txMgr = TransactionFactoryLoader.getInstance().getTransactionManager(); String driverName = jdbcElement.getJdbcDriver(); String jdbcUri = helperInfo.getOverrideJdbcUri(jdbcElement.getJdbcUri()); String jdbcUsername = helperInfo.getOverrideUsername(jdbcElement.getJdbcUsername()); String jdbcPassword = helperInfo.getOverridePassword(EntityConfig.getJdbcPassword(jdbcElement)); // pool settings int maxSize = jdbcElement.getPoolMaxsize(); int minSize = jdbcElement.getPoolMinsize(); int maxIdle = jdbcElement.getIdleMaxsize(); // maxIdle must be greater than pool-minsize maxIdle = maxIdle > minSize ? maxIdle : minSize; // load the driver Driver jdbcDriver; synchronized (DBCPConnectionFactory.class) { // Sync needed for MS SQL JDBC driver. See OFBIZ-5216. try { jdbcDriver = (Driver) Class .forName(driverName, true, Thread.currentThread().getContextClassLoader()).newInstance(); } catch (Exception e) { Debug.logError(e, module); throw new GenericEntityException(e.getMessage(), e); } } // connection factory properties Properties cfProps = new Properties(); cfProps.put("user", jdbcUsername); cfProps.put("password", jdbcPassword); // create the connection factory org.apache.commons.dbcp2.ConnectionFactory cf = new DriverConnectionFactory(jdbcDriver, jdbcUri, cfProps); // wrap it with a LocalXAConnectionFactory XAConnectionFactory xacf = new LocalXAConnectionFactory(txMgr, cf); // create the pool object factory PoolableConnectionFactory factory = new PoolableManagedConnectionFactory(xacf, null); factory.setValidationQuery(jdbcElement.getPoolJdbcTestStmt()); factory.setDefaultReadOnly(false); String transIso = jdbcElement.getIsolationLevel(); if (!transIso.isEmpty()) { if ("Serializable".equals(transIso)) { factory.setDefaultTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE); } else if ("RepeatableRead".equals(transIso)) { factory.setDefaultTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ); } else if ("ReadUncommitted".equals(transIso)) { factory.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED); } else if ("ReadCommitted".equals(transIso)) { factory.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); } else if ("None".equals(transIso)) { factory.setDefaultTransactionIsolation(Connection.TRANSACTION_NONE); } } // configure the pool settings GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig(); poolConfig.setMaxTotal(maxSize); // settings for idle connections poolConfig.setMaxIdle(maxIdle); poolConfig.setMinIdle(minSize); poolConfig.setTimeBetweenEvictionRunsMillis(jdbcElement.getTimeBetweenEvictionRunsMillis()); poolConfig.setMinEvictableIdleTimeMillis(-1); // disabled in favour of setSoftMinEvictableIdleTimeMillis(...) poolConfig.setSoftMinEvictableIdleTimeMillis(jdbcElement.getSoftMinEvictableIdleTimeMillis()); poolConfig.setNumTestsPerEvictionRun(maxSize); // test all the idle connections // settings for when the pool is exhausted poolConfig.setBlockWhenExhausted(true); // the thread requesting the connection waits if no connection is available poolConfig.setMaxWaitMillis(jdbcElement.getPoolSleeptime()); // throw an exception if, after getPoolSleeptime() ms, no connection is available for the requesting thread // settings for the execution of the validation query poolConfig.setTestOnCreate(jdbcElement.getTestOnCreate()); poolConfig.setTestOnBorrow(jdbcElement.getTestOnBorrow()); poolConfig.setTestOnReturn(jdbcElement.getTestOnReturn()); poolConfig.setTestWhileIdle(jdbcElement.getTestWhileIdle()); GenericObjectPool pool = new GenericObjectPool(factory, poolConfig); factory.setPool(pool); mds = new ManagedDataSource(pool, xacf.getTransactionRegistry()); //mds = new DebugManagedDataSource(pool, xacf.getTransactionRegistry()); // Useful to debug the usage of connections in the pool mds.setAccessToUnderlyingConnectionAllowed(true); // cache the pool dsCache.putIfAbsent(cacheKey, mds); mds = dsCache.get(cacheKey); return TransactionUtil.getCursorConnection(helperInfo, mds.getConnection()); }