JDBC MYSQL too many connections 两种解决方案

在这里插入图片描述

一、问题描述


使用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("静态块");
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

海若[MATRIX]

鼓励将是我最大的动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值