一、问题描述
使用java api创建mysql连接时,报错
too many connections
例如:工程中创建连接
//读取配置
Properties properties = new Properties();
try {
properties.load(new InputStreamReader(Objects.requireNonNull(Test.class.getClassLoader().getResourceAsStream("clusterKafkaConfigs.properties")), StandardCharsets.UTF_8));
} catch (IOException e) {
e.printStackTrace();
}
//创建mysql连接
try {
conn = MysqlUtils.connect(properties.get("mysql_host").toString(),
properties.get("mysql_port").toString()
, properties.get("mysql_user").toString(),
properties.get("mysql_password").toString());
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
二、解决方案1
show variables like "max_connections"; `
show global variables like 'wait_timeout';
使用上述命令在mysql命令行可查出,mysql默认最大连接数是200,连接等待时长是8小时,显然,如果你的连接数大于200,就会报错,连接太多。
因此你可以去mysql的配置文件中司改这两个参数,max_connections=10000,wait_timeout=200ms.
设置完,重启mysql,就可以解决。
解决方案2(终极解决方案)
方案一显然治标不治本,不过应对一般的场景足矣。
将mysql的连接创建放到静态语句块中,这样多次创建对象,就只创建一个连接,从根本上解决连接过多的问题!
static{
//读取配置
Properties properties = new Properties();
try {
properties.load(new InputStreamReader(Objects.requireNonNull(Test.class.getClassLoader().getResourceAsStream("clusterKafkaConfigs.properties")), StandardCharsets.UTF_8));
} catch (IOException e) {
e.printStackTrace();
}
//创建mysql连接
try {
conn = MysqlUtils.connect(properties.get("mysql_host").toString(),
properties.get("mysql_port").toString()
, properties.get("mysql_user").toString(),
properties.get("mysql_password").toString());
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
附录:(讲一讲静态语句快的原理,执行下面代码你就可以彻底理解为什么放到静态语句快中就可以解决连接过多的问题!)
public class test {
public static void main(String[] args) {
A a1 = new A();
A a2 = new A();
}
}
class A{
static{
System.out.println("静态块");
}
}