日期:2014-05-16  浏览次数:20435 次

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

最的一个项目,由原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());
	}
}

?

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

?

?

1 楼 ahgf 2011-04-29  
从代码上看不出什么问题。我的个人感觉是要检查每个获取Connection的地方,在使用完毕后,是否在finnally里关闭了。否则只要有一个地方没有关闭,就会越积越多,导致没有空闲连接可以获取。
下面是我以前用的监控数据库连接的语句,仅供参考:
select  machine,program,logon_time,status from v$session where schemaname='test' order by logon_time desc

select * from v$locked_object;

select  b.MACHINE, b.PROGRAM , count(*) from v$process a, v$session b where a.ADDR = b.PADDR and  b.USERNAME is not null   group by  b.MACHINE  , b.PROGRAM order by count(*) desc;
2 楼 hizhangqi 2011-05-05  
谢谢,已解决,的确是没有关闭。关闭之后目前没有出现问题.