【c3p0】报错:Initializing c3p0 pool... com.mchange.v2.c3p0.ComboPooledDataSource [ acquireIncrement...

来源:互联网 发布:软件开发工作进度表 编辑:程序博客网 时间:2024/05/30 20:08

按照书上的指导配置c3p0,但是运行不成功

一开始运行:

信息: Initializing c3p0 pool... com.mchange.v2.c3p0.ComboPooledDataSource [ acquireIncrement -> 3, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, dataSourceName -> 1hgeby99n2wpirj7phm07|69847c5d, debugUnreturnedConnectionStackTraces -> false, description -> null, driverClass -> com.mysql.jdbc.Driver, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, identityToken -> 1hgeby99n2wpirj7phm07|69847c5d, idleConnectionTestPeriod -> 

然后我刷新了十几次,报如下异常了:

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Data source rejected establishment of connection,  message from server: "Too many connections"

先来看看我配置数据库连接池的代码:

public static Connection getConnection() throws PropertyVetoException, SQLException{//c3p0连接池ComboPooledDataSource cpds = new ComboPooledDataSource();try {cpds.setDriverClass(DriverURL);} catch (PropertyVetoException e) {// TODO Auto-generated catch blocke.printStackTrace();}cpds.setJdbcUrl(ConURL);cpds.setUser(username);cpds.setPassword(passwoed);cpds.setMaxPoolSize(30);cpds.setMinPoolSize(2);cpds.setInitialPoolSize(10);cpds.setMaxStatements(180);return cpds.getConnection();}

结合异常声明:"Too many connections",才知道原来出错的地方就在这里:
ComboPooledDataSource cpds = new ComboPooledDataSource();

每次getConnection都会创建一个ComboPooledDataSource类,ComboPooledDataSource是重量级类,创建比较耗费资源,当然会报错

用单例模式来创建ComboPooledDataSource类即可解决问题:

private static ComboPooledDataSource ds;static{ds = new ComboPooledDataSource();try {ds.setDriverClass(DriverURL);} catch (PropertyVetoException e) {// TODO Auto-generated catch blocke.printStackTrace();}ds.setJdbcUrl(ConURL);ds.setUser(username);ds.setPassword(passwoed);ds.setMaxPoolSize(30);ds.setMinPoolSize(2);ds.setInitialPoolSize(10);ds.setMaxStatements(180);}
我是用饿汉式,然后对getConnection方法进行修改:

public static Connection getConnection() throws PropertyVetoException, SQLException{//用连接池return ds.getConnection();}



0 0
原创粉丝点击