我在尝试运行程序时遇到“连接太多”错误,该程序要求使用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");
}
答案 0 :(得分:4)
每次调用get_binary_list_from_decimal(1, 3)
#Return will be [0, 0, 1]
时,您都在创建一个全新的连接池。
您应该使用getConnection()
的单个共享实例。