如何为c3p0设置getConnection()超时



昨天AWS的RDS坏了,我们的数据库也坏了。

发生这种情况时,C3P0将尝试获得数据库连接并挂起。我显然希望我的应用程序在这些情况下返回一个错误页面,而不是永远等待响应。

代码如下:

ComboPooledDataSource db = new ComboPooledDataSource();
...
Connection conn = db.getConnection();

如何设置从c3p0的连接池获取连接的超时?

我认为checkoutTimeout()将是它-但它不是。它是"当连接池耗尽时,调用getConnection()的客户端等待签入或获取连接的毫秒数"。因为池没有耗尽(只是不可用),所以不适用

我也认为setacquireetryattempts和setAcquireIncrement会工作-但他们没有,因为连接没有失败,它只是不响应。

当我取出整个堆栈时,这是它停止的地方:

SocketInputStream.socketRead0(FileDescriptor, byte[], int, int, int) line: not available [native method]    
SocketInputStream.read(byte[], int, int) line: 129  
ReadAheadInputStream.fill(int) line: 113    
ReadAheadInputStream.readFromUnderlyingStreamIfNecessary(byte[], int, int) line: 160    
ReadAheadInputStream.read(byte[], int, int) line: 188   
MysqlIO.readFully(InputStream, byte[], int, int) line: 2428 
MysqlIO.reuseAndReadPacket(Buffer, int) line: 2882  
MysqlIO.reuseAndReadPacket(Buffer) line: 2871   
MysqlIO.checkErrorPacket(int) line: 3414    
MysqlIO.sendCommand(int, String, Buffer, boolean, String) line: 1936    
MysqlIO.sqlQueryDirect(StatementImpl, String, String, Buffer, int, int, int, boolean, String, Field[]) line: 2060   
JDBC4Connection(ConnectionImpl).execSQL(StatementImpl, String, int, Buffer, int, int, boolean, String, Field[], boolean) line: 2542 
JDBC4PreparedStatement(PreparedStatement).executeInternal(int, Buffer, boolean, boolean, Field[], boolean) line: 1734   
JDBC4PreparedStatement(PreparedStatement).executeQuery() line: 1885 
NewProxyPreparedStatement.executeQuery() line: 76   
C3P0PooledConnectionPoolManager.initializeAutomaticTestTable(String, DbAuth) line: 799  
C3P0PooledConnectionPoolManager.createPooledConnectionPool(DbAuth) line: 696    
C3P0PooledConnectionPoolManager.getPool(DbAuth) line: 257   
C3P0PooledConnectionPoolManager.getPool() line: 271 
ComboPooledDataSource(AbstractPoolBackedDataSource).getNumThreadsAwaitingCheckoutDefaultUser() line: 203    
NativeMethodAccessorImpl.invoke0(Method, Object, Object[]) line: not available [native method]  
NativeMethodAccessorImpl.invoke(Object, Object[]) line: 39  
DelegatingMethodAccessorImpl.invoke(Object, Object[]) line: 25  
Method.invoke(Object, Object...) line: 597  
BeansUtils.extractAccessiblePropertiesToMap(Map, Object, Collection) line: 359  
BeansUtils.appendPropNamesAndValues(StringBuffer, Object, Collection) line: 324 
ComboPooledDataSource.toString() line: 539  
ComboPooledDataSource(AbstractPoolBackedDataSource).getPoolManager() line: 462  
ComboPooledDataSource(AbstractPoolBackedDataSource).getConnection() line: 128   

当我搜索"socketRead0 timeout"and "socketRead0 hang"——我看到很多问题,但没有真正的解决办法。

这里是否有强制超时时间的方法?

这个问题是在MySQL的ReadAheadInputStream,它使用阻塞读取。本机套接字被阻塞并且从不(?)返回错误代码。所以连接也挂起了。

我看不到处理它的方法,除非把你的代码放到一个线程中,然后用超时来join()。我不认为这个问题有理由让事情变得复杂:我希望亚马逊能从停机时间中得出正确的结论,并且不要让这种情况再次发生。

那么,您可以在连接级别分配queryTimeout。IIRC, MySQL确实遵守这个。不知道C3P0会不会喜欢,但它可能会起作用。

最新更新