2016-08-31 103 views
0

当我尝试运行一个程序时,出现“太多连接”错误,该程序要求使用tomcat库实现的连接池进行连接,在大约50次连接后失败,这里是错误:Java - MySQL不关闭连接

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--; 
     } 

    } 

是执行一个简单的查询测试()函数

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()); 
     } 
     } 
    } 

,并询问从一个连接池

public Connection getConnection() throws SQLException 
    { 
     DataSource datasource = new DataSource(); 
     datasource.setPoolProperties(p); 

     Connection con = null; 
     con = datasource.getConnection(); 

     return con; 
    } 

编辑的连接的getConnection()类:这里是连接池设置:

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"); 
    } 
+2

连接池支持多少个连接?您可能希望将其限制为小于MySql可支持的连接数的最大连接数。 – alfasin

+0

我更新了帖子的池设置,我认为它被限制为MySql支持的最大连接数(默认为151) – Jose

回答

4

您正在创建一个完全新的连接每次调用getConnection()

您应该使用DataSource的单个共享实例。