欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

DBCP 老出异常 望各位给点意见 MySQLJDBCApache 

程序员文章站 2022-07-13 09:31:21
...

最的一个项目,由原JDBC 自写getConnection 改为apache dbcp 的连接池后。开始还不到出问题,但是数据访问频繁后,出如下错误

 

严重: 获取connection失败 :data=>org.apache.commons.dbcp.BasicDataSource@1cbb5ad:error=>Cannot get a connection, pool error Timeout waiting for idle object

 

 

public class ConnectionSource {

	private static Log logger = LogFactory
			.getLog("com.java.ods.framework.jdbc.ConnectionSource");

	private static BasicDataSource dataSource = null;

	public ConnectionSource() {
	}

	public static void init() {

		if (dataSource != null) {
			try {
				dataSource.close();
			} catch (Exception e) {
				logger.error("关闭dataSource失败 :data=>" + dataSource + ":error=>"
						+ e.getMessage());
			}
			dataSource = null;
		}

		try {
			Properties p = new Properties();

			p.setProperty("driverClassName", "com.mysql.jdbc.Driver");
			p
					.setProperty(
							"url",
							"jdbc:mysql://localhost:3306/orderDishesSystem?useUnicode=true&characterEncoding=gbk");
			p.setProperty("password", "mysql");
			p.setProperty("username", "root");
			p.setProperty("maxActive", "500");
			p.setProperty("maxIdle", "100");
			p.setProperty("maxWait", "1000");
			p.setProperty("removeAbandoned", "false");
			p.setProperty("removeAbandonedTimeout", "120");
			p.setProperty("testOnBorrow", "true");
			p.setProperty("logAbandoned", "true");

			dataSource = (BasicDataSource) BasicDataSourceFactory
					.createDataSource(p);

		} catch (Exception e) {
			logger.error("产出dataSource失败 :data=>" + dataSource + ":error=>"
					+ e.getMessage() + e);
		}
	}

	public static synchronized Connection getConnection() {
		Connection conn = null;
		try {
			if (dataSource == null) {
				init();
			}

			if (dataSource != null) {
				conn = dataSource.getConnection();
			}
		} catch (SQLException e) {
			logger.error("获取connection失败 :data=>" + dataSource + ":error=>"
					+ e.getMessage());
		}
		return conn;
	}

	public static void main(String[] args) {
		logger.info(ConnectionSource.getConnection());
	}
}

 

望各位指指招,小弟有礼了.

 

 

相关标签: MySQL JDBC Apache