我在尝试运行一个从使用 tomcat 库实现的连接池请求连接的程序时遇到“太多连接”错误,它在大约 50 个连接后失败,错误如下:
Exception in thread "main" com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Data source rejected establishment of connection, message from server: "Too many connections"
这是主类,它有一个执行连接的循环
public static void main(String[] args) throws Exception{
SimplePoolExample ex = new SimplePoolExample();
int cont = 100;
while (cont > 0)
{
ex.test();
System.out.println(cont);
cont--;
}
}
这是执行简单查询的 test() 函数
public void test() throws Exception
{
Connection con = getConnection();
try (Statement st = con.createStatement()) {
ResultSet rs = st.executeQuery("select * from actor");
while (rs.next()) {
System.out.println(rs.getString("actor_id") +" "+ rs.getString("first_name")+" "+ rs.getString("last_name"));
}
rs.close();
st.close();
} finally {
if (con!=null) try {
con.close();
}
catch (SQLException ignore) {
System.out.println("***SQL EXC" + ignore.getMessage());
}
}
}
和从连接池请求连接的 getConnection() 类
public Connection getConnection () throws SQLException
{
DataSource datasource = new DataSource();
datasource.setPoolProperties(p);
Connection con = null;
con = datasource.getConnection();
return con;
}
编辑:这里是连接池设置:
public void setPoolProperties ()
{
p.setUrl("jdbc:mysql://localhost:3306/sakila");
p.setDriverClassName("com.mysql.jdbc.Driver");
p.setUsername("user");
p.setPassword("pwd");
p.setJmxEnabled(true); // utilities to manage JVM
p.setTestWhileIdle(false); // test idle connections
p.setTestOnBorrow(true); //
p.setValidationQuery("SELECT 1"); // any test requires it
p.setTestOnReturn(false);
p.setValidationInterval(30000); // cada cuanto hace test
p.setTimeBetweenEvictionRunsMillis(30000); // how often check idle and abandoned conn
p.setMaxActive(50);
p.setInitialSize(10);
p.setMaxWait(50);
p.setRemoveAbandonedTimeout(60); // OJO: max query last
p.setMinEvictableIdleTimeMillis(30000); // time to consider a conn idle
p.setMaxIdle(10);
p.setMinIdle(10);
p.setLogAbandoned(true); // log stack traces .. overhead
p.setRemoveAbandoned(true); //abandoned timeout ...
p.setJdbcInterceptors(
"org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;"+
"org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer");
}
最佳答案
每次调用 getConnection()
时,您都在创建一个全新的连接池。
您应该改用 DataSource
的单个共享实例。
关于Java - MySQL 不关闭连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39259842/