依赖tomcat 就不一样了:
配置数据库dbcp
我测试过培植如下:
<Resource name="jdbc/TestDB"
auth="Container"
type="javax.sql.DataSource" username="root" password="sa" maxActive = "3" maxIdle = "30" maxWait = "10000"
testOnBorrow = "true" testOnReturn = "true" testWhileIdle = "true"
validationQuery = " select 1 "
driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/db_wis"/>
</Context>
web.xml
<resource-ref>
<res-ref-name>jdbc/TestDB </res-ref-name>
<res-type>javax.sql.DataSource </res-type>
<res-auth>Container </res-auth>
</resource-ref>
java 代码:
public static void show()
{
javax.sql.DataSource ds = null;
System.out.println(" ------------------- show()");
try{
Context ctx = new InitialContext();
if(ctx == null)
throw new Exception("no Context!");
System.out.print(" >>>>> " + ctx.lookup("java:comp/env/jdbc/TestDB").getClass());
ds = (DataSource)ctx.lookup("java:comp/env/jdbc/TestDB");
}catch(Exception e)
{
System.out.println(e.getMessage());
return;
}
Connection testconnection = null;
try{
testconnection = ds.getConnection();
System.out.println(testconnection.hashCode() + ">>>> " + testconnection.isClosed() );
Statement statement = testconnection.createStatement();
ResultSet resultSet = statement.executeQuery("select * from wis_admin_user");
while(resultSet.next())
{
System.out.println("resultSet.getInt(2) = " + resultSet.getString(2));
}
if(resultSet != null)
resultSet.close();
}catch(Exception ex)
{
ex.printStackTrace();
}
finally
{
try{
if(testconnection != null)
{
if(!testconnection.isClosed())
testconnection.close();
}
}catch(Exception ex){
ex.printStackTrace();
}
}
}
测试的:
1:如果是: <Resource name="jdbc/TestDB"
auth="Container"
type="javax.sql.DataSource" username="root" password="sa" maxActive = "3" maxIdle = "30" maxWait = "10000"
driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/db_wis"/>
</Context>
会出错,时间超过了mysql wait_timeout ,interactive_timeout(我设置的是5秒)连接断掉后,它的物理连接断掉了.
pools 里面的连接对象没删除.超过了3个死掉了.更本不行不通.
2:如果是
<Resource name="jdbc/TestDB"
auth="Container"
type="javax.sql.DataSource" username="root" password="sa" maxActive = "3" maxIdle = "30" maxWait = "10000"
driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/db_wis?autoReconnect=true"/>
会出错,时间超过了mysql wait_timeout ,interactive_timeout(我设置的是5秒)连接断掉后,它的物理连接断掉了.
pools 里面的连接对象 会出现一次异常,tomcat 会自动去连接,如果在超过 5 秒没用,又会断开,如此下去.(这样的话
在写程序我门要做异常处理,在异常里重新取得连接,照样可以)
3:如果是
<Resource name="jdbc/TestDB"
auth="Container"
type="javax.sql.DataSource" username="root" password="sa" maxActive = "3" maxIdle = "30" maxWait = "10000"
testOnBorrow = "true" testOnReturn = "true" testWhileIdle = "true"
validationQuery = " select 1 "
driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/db_wis"/>
</Context>
是我们开发过程最好的选择:
如果连接取连接会检测物理连接是否断掉,如果断掉,就会在pools remove 断掉了的代理连接.不会挂掉的.(就会象第一种测试那样挂掉的 因为我们设置的maxActive = 3 活动对象最大数是3 ,但它的物理连接都断掉了)
注意 validationQuery 是一定要的;(如果没有,设置testOnBorrow,testOnReturn,testWhileIdle 无效的)
JDBC begin failed解决方案
最新推荐文章于 2025-05-15 17:12:29 发布