In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >
Share
Shulou(Shulou.com)06/01 Report--
During the construction of C3p0, there are driver-related information and database connection pool-related property settings, and connection acquisition. Today, let's take a look at driver-related information and database connection pool-related property settings in connection acquisition.
Start with the following sentences
Java code
CpDSource = new ComboPooledDataSource ()
/ / set DriverManagerDataSource driver related information
CpDSource.setDriverClass (props.getProperty ("driver"))
CpDSource.setJdbcUrl (props.getProperty ("url"))
CpDSource.setUser (props.getProperty ("user"))
CpDSource.setPassword (props.getProperty ("password"))
/ / DriverManagerDataSource,WrapperConnectionPoolDataSource, two key internal members of AbstractComboPooledDataSource
Java code download
Public AbstractComboPooledDataSource (boolean autoregister)
{
/ /
Super (autoregister)
/ / create a new driver data source manager
Dmds = new DriverManagerDataSource ()
/ / create a new database connection pool
Wcpds = new WrapperConnectionPoolDataSource ()
/ / set the data source driver manager for the data connection pool
Wcpds.setNestedDataSource (dmds)
Try
{
SetConnectionPoolDataSource (wcpds)
}
Catch (PropertyVetoException e)
{
Logger.log (MLevel.WARNING, "Hunh??? This can't happen. We haven't set up any listeners to veto the property change yet!", e)
Throw new RuntimeException ((new StringBuilder ()) .append ("Hunh??? This can't happen. We haven't set up any listeners to veto the property change yet!") .append (e) .append ()
}
SetUpPropertyEvents ()
}
}
/ / set driverClass
Public void setDriverClass (String driverClass)
Throws PropertyVetoException
{
Dmds.setDriverClass (driverClass)
}
/ / set jdbcUrl
Public void setJdbcUrl (String jdbcUrl)
{
If (diff (dmds.getJdbcUrl (), jdbcUrl))
{
Dmds.setJdbcUrl (jdbcUrl)
ResetPoolManager (false)
}
}
/ / set user
Public void setUser (String user)
{
If (diff (dmds.getUser (), user))
{
Dmds.setUser (user)
ResetPoolManager (false)
}
}
/ / set password
Public void setPassword (String password)
{
If (diff (dmds.getPassword (), password))
{
Dmds.setPassword (password)
ResetPoolManager (false)
}
}
/ / set WrapperConnectionPoolDataSource related properties
Java code download
CpDSource.setInitialPoolSize (5)
CpDSource.setMaxPoolSize (30)
CpDSource.setMinPoolSize (5)
CpDSource.setMaxStatements (100)
CpDSource.setIdleConnectionTestPeriod (60)
CpDSource.setBreakAfterAcquireFailure (false)
CpDSource.setAcquireRetryAttempts (30)
CpDSource.setTestConnectionOnCheckout (false)
/ / set the number of failed connection attempts
Java code
Public void setAcquireRetryAttempts (int acquireRetryAttempts)
{
If (diff (wcpds.getAcquireRetryAttempts (), acquireRetryAttempts))
{
Wcpds.setAcquireRetryAttempts (acquireRetryAttempts)
ResetPoolManager (false)
}
}
Public int getAcquireRetryDelay ()
{
Return wcpds.getAcquireRetryDelay ()
}
Public void setAcquireRetryDelay (int acquireRetryDelay)
{
If (diff (wcpds.getAcquireRetryDelay (), acquireRetryDelay))
{
Wcpds.setAcquireRetryDelay (acquireRetryDelay)
ResetPoolManager (false)
}
}
Public boolean isAutoCommitOnClose ()
{
Return wcpds.isAutoCommitOnClose ()
}
/ / set whether to submit automatically
Public void setAutoCommitOnClose (boolean autoCommitOnClose)
{
If (diff (wcpds.isAutoCommitOnClose (), autoCommitOnClose))
{
Wcpds.setAutoCommitOnClose (autoCommitOnClose)
ResetPoolManager (false)
}
}
Public int getInitialPoolSize ()
{
Return wcpds.getInitialPoolSize ()
}
/ / connection pool initialization size
Public void setInitialPoolSize (int initialPoolSize)
{
If (diff (wcpds.getInitialPoolSize (), initialPoolSize))
{
Wcpds.setInitialPoolSize (initialPoolSize)
ResetPoolManager (false)
}
}
download
Public int getMaxIdleTime ()
{
Return wcpds.getMaxIdleTime ()
}
/ / maxIdleTime
Public void setMaxIdleTime (int maxIdleTime)
{
If (diff (wcpds.getMaxIdleTime (), maxIdleTime))
{
Wcpds.setMaxIdleTime (maxIdleTime)
ResetPoolManager (false)
}
}
/ / maxPoolSize
Public void setMaxPoolSize (int maxPoolSize)
{
If (diff (wcpds.getMaxPoolSize (), maxPoolSize))
{
Wcpds.setMaxPoolSize (maxPoolSize)
ResetPoolManager (false)
}
}
/ / maxStatements
Public void setMaxStatements (int maxStatements)
{
If (diff (wcpds.getMaxStatements (), maxStatements))
{
Wcpds.setMaxStatements (maxStatements)
ResetPoolManager (false)
}
}
From the above, you can see that cpDSource initializes the attributes related to driver, which initializes the attributes of the data source driver manager DriverManagerDataSource, and initializes the attributes related to poolConnection, which initializes the database connection pool wrapper class WrapperConnectionPoolDataSource.
Let's look at the acquisition of the connection, starting with the following sentence.
Java code
Con = cpDSource.getConnection ()
This method is not found in ComboPooledDataSource or its parent class, dating back to the
Parent class AbstractPoolBackedDataSource
/ / AbstractPoolBackedDataSource
Java code
Public abstract class AbstractPoolBackedDataSource extends PoolBackedDataSourceBase
Implements PooledDataSource
{
Public Connection getConnection ()
Throws SQLException
{
/ / get the database connection pool manager
PooledConnection pc = getPoolManager (). GetPool (). CheckoutPooledConnection ()
/ / return the database connection from the database connection pool
Return pc.getConnection ()
}
}
Let's take a look at getting the database connection pool manager.
/ / get the database connection pool manager
PooledConnection pc = getPoolManager (). GetPool (). CheckoutPooledConnection ()
/ / get the database connection pool manager
download
Java code
Private synchronized C3P0PooledConnectionPoolManager getPoolManager ()
Throws SQLException
{
If (poolManager = = null)
{
/ / get data source database connection pool
ConnectionPoolDataSource cpds = assertCpds ()
/ / build a database connection pool manager
PoolManager = new C3P0PooledConnectionPoolManager (cpds, null, null, getNumHelperThreads (), getIdentityToken (), getDataSourceName ())
If (logger.isLoggable (MLevel.INFO))
Logger.info ((new StringBuilder ()) .append ("Initializing c3p0 pool...") .append (toString (true)) .toString ())
}
Return poolManager
}
/ / determine the data source database connection pool
Private synchronized ConnectionPoolDataSource assertCpds ()
Throws SQLException
{
If (is_closed)
Throw new SQLException ((new StringBuilder ()) .append (this) .append ("has been closed ()-- you can no longer use it.") .toString ())
/ / get data source database connection pool
ConnectionPoolDataSource out = getConnectionPoolDataSource ()
If (out = = null)
Throw new SQLException ("Attempted to use an uninitialized PoolBackedDataSource. Please call setConnectionPoolDataSource (...) to initialize.")
Else
Return out
}
/ / PoolBackedDataSourceBase
Java code
Public class PoolBackedDataSourceBase extends IdentityTokenResolvable
Implements Referenceable, Serializable
{
/ / get data source database connection pool
Public synchronized ConnectionPoolDataSource getConnectionPoolDataSource ()
{
Return connectionPoolDataSource
}
Public synchronized void setConnectionPoolDataSource (ConnectionPoolDataSource connectionPoolDataSource)
Throws PropertyVetoException
{
ConnectionPoolDataSource oldVal = this.connectionPoolDataSource
If (! eqOrBothNull (oldVal, connectionPoolDataSource))
Vcs.fireVetoableChange ("connectionPoolDataSource", oldVal, connectionPoolDataSource)
This.connectionPoolDataSource = connectionPoolDataSource
If (! eqOrBothNull (oldVal, connectionPoolDataSource))
Pcs.firePropertyChange ("connectionPoolDataSource", oldVal, connectionPoolDataSource)
}
}
What is this data source data connection pool? Remember before, we talked about the construction of AbstractComboPooledDataSource.
Java code download
Public AbstractComboPooledDataSource (boolean autoregister)
{
Super (autoregister)
Dmds = new DriverManagerDataSource ()
Wcpds = new WrapperConnectionPoolDataSource ()
Wcpds.setNestedDataSource (dmds)
Try
{
/ / set the data source database connection pool to WrapperConnectionPoolDataSource
SetConnectionPoolDataSource (wcpds)
}
}
Now go back to the sentence of getPoolManager's build database connection pool manager
Java code
PoolManager = new C3P0PooledConnectionPoolManager (cpds, null, null, getNumHelperThreads (), getIdentityToken (), getDataSourceName ())
/ / C3P0PooledConnectionPoolManager
Java code
Public final class C3P0PooledConnectionPoolManager
{
Private static final boolean POOL_EVENT_SUPPORT = false
Private static final CoalesceChecker COALESCE_CHECKER
Static final Coalescer COALESCER
Static final int DFLT_NUM_TASK_THREADS_PER_DATA_SOURCE = 3
ThreadPoolAsynchronousRunner taskRunner;//
ThreadPoolAsynchronousRunner deferredStatementDestroyer
Timer timer
ResourcePoolFactory rpfact
Map authsToPools
Final ConnectionPoolDataSource cpds
Final Map propNamesToReadMethods
Final Map flatPropertyOverrides
Final Map userOverrides
Final DbAuth defaultAuth
Final String parentDataSourceIdentityToken
Final String parentDataSourceName
Int num_task_threads
Static
{
COALESCE_CHECKER = IdentityTokenizedCoalesceChecker.INSTANCE
COALESCER = CoalescerFactory.createCoalescer (COALESCE_CHECKER, true, false)
}
/ / initialize C3P0PooledConnectionPoolManagerJournal cpds to WrapperConnectionPoolDataSource
Public C3P0PooledConnectionPoolManager (ConnectionPoolDataSource cpds, Map flatPropertyOverrides, Map forceUserOverrides, int num_task_threads, String parentDataSourceIdentityToken, String parentDataSourceName)
Throws SQLException
{
/ / number of task threads
This.num_task_threads = 3
Try
{
This.cpds = cpds;// initializes the database connection pool
This.flatPropertyOverrides = flatPropertyOverrides
This.num_task_threads = num_task_threads
This.parentDataSourceIdentityToken = parentDataSourceIdentityToken
This.parentDataSourceName = parentDataSourceName
DbAuth auth = null
If (flatPropertyOverrides! = null)
{
String overrideUser = (String) flatPropertyOverrides.get ("overrideDefaultUser")
String overridePassword = (String) flatPropertyOverrides.get ("overrideDefaultPassword")
If (overrideUser = = null)
{
OverrideUser = (String) flatPropertyOverrides.get ("user")
OverridePassword = (String) flatPropertyOverrides.get ("password")
}
If (overrideUser! = null)
Auth = new DbAuth (overrideUser, overridePassword)
}
If (auth = = null)
/ / initialize database verification
Auth = C3P0ImplUtils.findAuth (cpds)
DefaultAuth = auth
Map tmp = new HashMap ()
BeanInfo bi = Introspector.getBeanInfo (cpds.getClass ())
PropertyDescriptor pds [] = bi.getPropertyDescriptors ()
PropertyDescriptor pd = null
Int I = 0
For (int len = pds.length; I
< len; i++) { 下载 pd = pds[i]; String name = pd.getName(); Method m = pd.getReadMethod(); if(m != null) tmp.put(name, m); } propNamesToReadMethods = tmp; if(forceUserOverrides == null) { Method uom = (Method)propNamesToReadMethods.get("userOverridesAsString"); if(uom != null) { String uoas = (String)uom.invoke(cpds, (Object[])null); Map uo = C3P0ImplUtils.parseUserOverridesAsString(uoas); userOverrides = uo; } else { userOverrides = Collections.EMPTY_MAP; } } else { userOverrides = forceUserOverrides; } poolsInit(); } catch(Exception e) { logger.log(MLevel.FINE, null, e); throw SqlUtils.toSQLException(e); } } } //连接池初始化 private void poolsInit() { boolean privilege_spawned_threads = getPrivilegeSpawnedThreads(); String contextClassLoaderSource = getContextClassLoaderSource(); class _cls1ContextClassLoaderPoolsInitThread extends Thread { public void run() { // maybePrivilegedPoolsInit(privilege_spawned_threads); } final boolean val$privilege_spawned_threads; final C3P0PooledConnectionPoolManager this$0; _cls1ContextClassLoaderPoolsInitThread(boolean flag) { this.this$0 = C3P0PooledConnectionPoolManager.this; privilege_spawned_threads = flag; super(); setContextClassLoader(ccl); } } try { if("library".equalsIgnoreCase(contextClassLoaderSource)) { // Thread t = new _cls1ContextClassLoaderPoolsInitThread(privilege_spawned_threads); t.start(); t.join(); } else if("none".equalsIgnoreCase(contextClassLoaderSource)) { Thread t = new _cls1ContextClassLoaderPoolsInitThread(privilege_spawned_threads); t.start(); t.join(); } else { if(logger.isLoggable(MLevel.WARNING) && !"caller".equalsIgnoreCase(contextClassLoaderSource)) logger.log(MLevel.WARNING, (new StringBuilder()).append("Unknown contextClassLoaderSource: ").append(contextClassLoaderSource).append(" -- should be 'caller', 'library', or 'none'. Using default value 'caller'.").toString()); maybePrivilegedPoolsInit(privilege_spawned_threads); } } } private void maybePrivilegedPoolsInit(boolean privilege_spawned_threads) { if(privilege_spawned_threads) { PrivilegedAction privilegedPoolsInit = new PrivilegedAction() { public Void run() { //委托给_poolsInit _poolsInit(); return null; } public volatile Object run() { return run(); } final C3P0PooledConnectionPoolManager this$0; { this.this$0 = C3P0PooledConnectionPoolManager.this; super(); } }; AccessController.doPrivileged(privilegedPoolsInit); } else { _poolsInit(); } } //终于找个了poolsInit的关键,初始化定时任务调度器,及死锁检测线程,及延时死锁检测线程 private synchronized void _poolsInit() { String idStr = idString(); timer = new Timer((new StringBuilder()).append(idStr).append("-AdminTaskTimer").toString(), true); int matt = getMaxAdministrativeTaskTime(); //创建任务线程调度器 taskRunner = createTaskRunner(num_task_threads, matt, timer, (new StringBuilder()).append(idStr).append("-HelperThread").toString()); int num_deferred_close_threads = getStatementCacheNumDeferredCloseThreads(); if(num_deferred_close_threads >0)
DeferredStatementDestroyer = createTaskRunner (num_deferred_close_threads, matt, timer, (new StringBuilder ()) .append (idStr) .append ("- DeferredStatementDestroyerThread") .toString ())
Else
DeferredStatementDestroyer = null
Rpfact = BasicResourcePoolFactory.createNoEventSupportInstance (taskRunner, timer)
AuthsToPools = new HashMap ()
}
You can see from the above that getPoolManager () actually initializes the database connection pool manager C3P0PooledConnectionPoolManager and initializes the C3P0PooledConnectionPoolManager
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.